|
|
|
|
|
|
|
This associativity makes sense because the assignment operation is naturally a right-to-left operation. |
|
|
|
|
|
|
|
|
A word of caution: Although operator precedence and associativity dictate the grouping of operators with their operands, C++ does not define the order in which subexpressions are evaluated. Therefore, using side effects in expressions requires extra care. For example, if i currently contains 5, the statement |
|
|
|
|
|
|
|
|
stores either 11 or 12 into j, depending on the particular compiler being used. Let's see why. There are three operators in the expression statement above: =, ++, and +. The ++ operator has the highest precedence, so it operates just on i, not the expressioni + i. The addition operator has higher precedence than the assignment operator, giving implicit parentheses as follows: |
|
|
|
|
|
|
|
|
So far, so good. But now we ask this question: In the addition operation, is the left operand or the right operand evaluated first? The C++ language doesn't define the order. If a compiler generates code to evaluate the left operand first, the result is 6 + 6, or 12. Another compiler might generate code to evaluate the right operand first, yielding 5 + 6, or 11. To be assured of left-to-right evaluation in this example, you should force the ordering with two separate statements: |
|
|
|
|
|
|
|
|
The moral here is that if you use multiple side effects in expressions, you increase the risk of unexpected or inconsistent results. For the newcomer to C++, it's better to avoid unnecessary side effects altogether. |
|
|
|
|
|
|
|
|
Working with Character Data |
|
|
|
|
|
|
|
|
Because char is an integral type and sizeof(char) equals 1, a char variable can store a small (one-byte) integer constant. For example, |
|
|
|
|
|
|
|
|
char counter;
.
.
.
counter = 3; |
|
|
|
|
|