Home Segments Index Top Previous Next

316: Mainline

You can, in principle, embed expressions involving the increment operator, ++, or the decrement operator, --, in larger expressions, such as the following:

++x + x         // Bad:  never do this 

In such an expression, the increment operator, ++, is said not only to produce a value, but also to have the side effect of incrementing x.

Importantly, however, the C++ language does not prescribe the order in which operands are evaluated in arithmetic expressions. Thus, in the expression ++x + x, the left-side operand, ++x, may be evaluated either before or after the right-side operand, x, depending on the implementation.

Suppose, for example, that the initial value of x is 0. In an implementation that evaluates left-side first, the value of ++x + x will be 2; on the other hand, in an implementation that evaluates right-side first, the value of ++x + x will be 1.

Thus, the use of side-effect operators, such as ++ and --, can lead to mysterious portability problems.

Worse yet, a C++ compiler is free to compile some expressions for left-side-first evaluation and others for right-side-first evaluation. Thus, side-effect operands can cause plenty of trouble.