Friday, August 14, 2009


As mentioned earlier, data alone is not enough, we need ways to process and manipulate it. Operator can be used together with data to form expressions that produce a data value of certain value, i.e. 2+3-1.

C++ operators

-->. > [] () var++ var
<--! expr +expr ++var var &var *expr sizeof new delete
-->* / %
--><< >>
-->< <= > >=
-->== !=
<--= *= /= += = <<= >>= &= |= ^=
-->expr ? expr : expr
-->expr , expr

Operator precedence

The order of evaluation in an expression is determined by operator precedence (or priority). The operator is evaluated the earlier the higher it is in the table. Parenthesis can be used to change the usual order of evaluation. The operator ? and - can be used as unary (i.e. they can be applied to a single operand) or binary operators (two operands). The unary operators have a higher precedence. For example, the statement:

a = 4 / 2 + -3 * 2;

is evaluated as

( a = ( ( 4 / 2 ) + ( ( -3 ) * 2 ) ) );

The same basic principles apply here as in maths. C++ just has more operators. Evaluation results (usually) in a value that can be used as an operand for another operator. The result of arithmetic operators is of the same type as their operands.

Extra care must be take with division. For example 3/4 produces an integer quotient = since both operands are integers.The expression 3.0/4, however, produces the "exact" value 0.75 even though only one operand is real number.

C++ often automatically widens the "narrower" value so that the expression can be evaluated. The type can (and should) be explicitly converted.

static_cast<> ( 1 ) produces 1.0 as a result. As a rule, if the operands are of different types, the result is of the wider type.

Operator associativity

When the expression has several operators with the same level of precedence, the evaluation order cannot be determined from the precedence rules alone. The associativity rules of the language define which operator is evaluated first. An operator can either have left (leftmost operators are evaluated first) or right (right most operators are evaluated first) associativity. In the given table the arrows in the left tell the associativity of the operators in the table. For example

9 -5 - 2 - 1 is evaluated as (((9 - 5) - 2) - 1)

Associativity is important in overflow and underflow situations and with round-off errors.

Previous post

Next post

No comments:

Post a Comment