Operators and Expressions


Expressions are built using operators that work with data—the operands—to give a result. Look at this example:

Remuneration = Salary + Bonus;

Here the addition operator + (a plus sign) is used to add the operands Salary and Bonus, and the assignment operator = (an equal sign) is used to store the total in the Remuneration variable.

Assignment Operators

An assignment expression is used to assign a value to a variable. All expressions return a value when evaluated, and the value of the assignment expression is the new value of the object on the left side. This functionality makes it possible to assign the same value to a group of variables.

NoOfMammals = NoOfDogs = NoOfCats = 0;

In this example, all three variables—NoOfMammals, NoOfDogs, and NoOfCats—are set to 0.

Arithmetic Operators

C++ has 12 arithmetic operators, five of which operate like the standard mathematical operators: the addition operator + (a plus sign), the subtraction operator - (a minus sign), the multiplication operator * (an asterisk), the division operator / (a slash), and the modulus operator % (a percentage sign), which returns the remainder after division.

Result = 4 + 2 - 3; // Result = 3 Result = 4 * 5; // Result = 20 Remainder = 7 % 3; // Remainder = 1

In addition, there are a number of arithmetic assignment operators: the addition assignment operator += (a plus sign with an equal sign), the subtraction assignment operator -= (a minus sign with an equal sign), the multiplication assignment operator *= (an asterisk with an equal sign), the division assignment operator / = (a slash with an equal sign), and the modulus assignment operator %= (a percentage sign with an equal sign). These operators are shorthand forms that combine the corresponding mathematical operation with the assignment operation. So, A = A + 5; could be expressed as A += 5;.

Instead of using the addition operator to add 5 to the value of the variable A and then using the assignment operator to assign the new value to the variable A, you can just use the addition assignment operator to add 5 to the value of the variable A and assign the new value. The addition assignment operator is a shortcut operator. There is no difference between the two statements. In both statements, an addition is performed, followed by an assignment. The second form is just a shorter way of expressing a frequently used operation.

The increment and decrement operators are similar shorthand operators, but these operators only add or subtract 1 from the value of the variable:

A++; // Adds 1 to the value of the variable A. A--; // Subtracts 1 from the value of the variable A.

There are two forms of the increment and decrement operators: the prefix form ++A or --A, and the postfix forms A++ or A--. Both forms add or subtract 1 to the variable. In the prefix form, the mathematical operation is performed before the variable’s role in the expression is evaluated; in the postfix form, the variable is incremented or decremented after the variable has been used in the expression.

int a, b, c; a = b = c = 0; b = ++a; // a = 1, b = 1 c = a++; // c = 1, a = 2

In this code fragment, the final values of the variables are a = 2, b = 1, and c = 1. The prefix increment operator expression added 1 to the value of a before assigning the value of the variable a to the variable b. The postfix increment operator expression assigned the value of the variable a to the variable c and then incremented the value of the variable a by 1.

Note

When working with objects, the prefix versions of the increment and decrement operators are more efficient than the postfix versions because a temporary copy of the object doesn’t have to be made for use in the expression before incrementing or decrementing the object.

Relational and Logical Operators

Relational operators are used to compare two values or expressions, returning a true or false value. C++ has six relational operators: the greater than operator > (a right angle bracket), the greater than or equal operator >= (a right angle bracket with an equal sign), the less than operator < (a left angle bracket), the less than or equal operator <= (a left angle bracket with an equal sign), the equal operator == (two equal signs), and the not equal operator != (an exclamation point with an equal sign).

a > b // returns true if a is greater than b. a >= b // returns true if a is greater than or equal to b. a < b // returns true if a is less than b. a <= b // returns true if a is less than or equal to b. a == b // returns true if a is equal to b. a != b // returns true if a is not equal to b.

A logical operator is used to relate two relational expressions. C++ has three logical operators: the AND operator && (two ampersands), the OR operator || (two pipes), and the NOT operator ! (an exclamation point). The AND operator relates two expressions, both of which must be true for the operator to return a true value. The OR operator returns true if either of the two expressions evaluates to true.

a && b // returns true if both a and b are true (a > b) && (a < c) // returns true if a is greater than b and a // is less than c a || b // returns true if either a or b are true (a > b) || (a < c) // returns true if either a is greater than b // or a is less than c

The evaluation of a relational expression stops as soon as the logical value of the whole expression is determined. For example, the expression expr1 && expr2 is true only if both expr1 and expr2 are true. If expr1 is false, the final value of the expression must be false, and therefore, expr2 is not evaluated.

The NOT operator returns the negation of the Boolean value of its operand:

!a // If a is true the NOT operator will return false, if a is // false the NOT operator will return true.

These operators are most often used in decision or loop structures, which will be discussed in Chapter 5.

Bitwise Operators

C++ has six bitwise operators: the AND operator & (an ampersand), the OR operator | (a pipe), the exclusive OR operator ^ (a caret), the complement operator ~ (a tilde), the right shift operator >> (two right angle brackets), and the left shift operator << (two left angle brackets). These operators work on the individual bits of the byte and can only be applied to integral operands—the types char, short, int, and long. The bitwise AND operator compares the bits of two operands; if the bit in the same position for each operand is 1, the resulting bit is 1; if, however, either bit is 0 the resulting bit is set to 0. This operator is often used to mask off bits.

The bitwise OR operator compares the bits of two operands: if either bit is 1, the corresponding bit of the result is 1, and if both bits are 0, the corresponding bit of the result is set to 0. The bitwise OR operator is often used to turn bits, flags, or options on.

The exclusive OR operator sets the result bit to 1 only if one of the operands has the corresponding bit set to 1. If the corresponding bit of both operands is 1 or 0, the bit is set to 0.

The complement operator reverses the bit setting of the operand. If the bit is 1, it is set to 0; if the bit is 0, it is set to 1.

The left shift operator moves the bit pattern of its left operand to the left by the number of bits specified by its right operand. The bits vacated by the left shift are filled with zeros. The right shift operator moves the bit pattern of its right operand to the right by the number of bits specified by its right operand. If the variable is an unsigned data type, the vacated bits will be filled with zeros; if the variable is signed, the vacated bits will be filled with the sign bit.

int a; a = 5; a = a << 2; // The bits of a will be shifted two bits to the left // and the value of 20 assigned to a a = 5; a = a >> 2; // The bits of a will be shifted two bits to the // right and the value of 1 assigned to a

The Ternary Operator

The ternary operator ?: (composed of a question mark and a colon) is an inline if statement. (See Chapter 5 for more information on if statements.) The expression to the left of the ternary operator is evaluated: if it is true, the value or expression between the ternary operator and the colon is returned. If it is false, the value or expression after the colon is returned.

int a; bool b; b = true; a = b ? 1 : 2; // b is true, so a is assigned 1. b = false; a = b ? 1 : 2; // b is false, so a is assigned 2.

The sizeof Operator

The sizeof operator returns the size of the C++ data type, either built-in or user- defined, in bytes. For example, sizeof(int) and sizeof(animal).

Type Casting

C++ supports the C-style cast operator, where the type you want to convert the expression to is placed in parentheses in front of the expression; for example, (float) 7. It also supports four new cast operators:

  • static_cast<type>

  • const_cast<type>

  • dynamic_cast<type>

  • reinterpret_cast<type>

The static_cast<type> operator changes the data type of the variable. For example, if an expression needs to convert an integer into a floating-point number for a calculation, the number should be cast using the static_cast<double> operator. The dynamic_cast<type> operator is used to cast objects down or across the inheritance hierarchy. The const_cast<type> operator changes the const-ness of the variable. The reinterpret_cast<type> operator allows any pointer to be converted into a pointer of another type.

int a = 10; double b; b = (double) a; // old C style cast operator b = static_cast<double>(a); // C++ static_cast operator

Operator Precedence and Associativity

There are two ways in which the expression 2 + 3 * 4 could be evaluated: it could be evaluated as (2 + 3) * 4, giving a value of 20, or it could be evaluated as 2 + (3 * 4), giving a value of 14.

The rules of operator precedence allow an unambiguous evaluation of expressions. Operators higher in the hierarchy are given precedence over operators lower in the hierarchy. Because the * operator is higher than the + operator, the second interpretation of the above expression, 2 + (3 * 4), would be evaluated. In situations where two operators are at the same level in the hierarchy, the order of evaluation proceeds from left to right. Hence, 2 * 3 / 2 * 3 would be evaluated as ((2 * 3) / 2) * 3, giving a value of 9. Parentheses can be used to group operators and override the precedence hierarchy. For example, (2 * 3) / (2 * 3), giving a value of 1. Ideally, you should use parentheses even when they are not strictly required simply to clarify your intentions. The following table shows the hierarchy of precedence from highest to lowest. Operators in the same row of the table share the same level of precedence.

Operator

Name

::

Scope resolution

. -> [] () ++ --

Member selection, subscripting, function calls, postfix increment, postfix decrement, casting operators

static_cast<type>

const_cast<type>

dynamic_cast<type>

reinterpret_cast<type>

sizeof() ++ --

sizeof(), prefix increment, prefix decrement, complement, not, unary minus, unary plus, address of, dereference, new, delete, delete[]

^ ! - + & * new

delete delete[]

.* ->*

Pointer to member operator

* / %

Multiply, divide, modulus

+ -

Add, subtract

>> <<

Right shift, left shift

< <= > >=

Relational operators (inequality)

== !=

Equality, inequality

&

Bitwise AND

^

Exclusive OR

|

Bitwise OR

&&

Logical AND

||

Logical OR

?:

Ternary operator

= += -= *= /= %

Assignment operators

= <<= >>= &= |= ^=

,

Comma




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net