> The result of an expression using pre-decrement or pre-increment such as: > y = x * n * --n; > gives different results in a few cases where x is placed before or after > the rest, or when its value is 1 or not. Please run the program attached > where a comment indicates what we think works wrong. We obtain: > > 1.- 16 > 2.- 16 > 3.- 16 > 4.- 40 > 5.- 20 > 6.- 16 > 7.- 40 > 8.- 32 > 1.- 36 > 2.- 36 > 3.- 36 > 4.- 60 > 5.- 30 > 6.- 36 > 7.- 60 > 8.- 72 > > In contrast, the results we get running it in a AIX Computer with the > native compiler (IBM XL C/C++ Enterprise Edition for AIX, V9.0 Version: > 09.00.0000.0000) is what we expected: > > 1.- 20 > 2.- 20 > 3.- 20 > 4.- 40 > 5.- 20 > 6.- 20 > 7.- 40 > 8.- 40 > 1.- 30 > 2.- 30 > 3.- 30 > 4.- 60 > 5.- 30 > 6.- 30 > 7.- 60 > 8.- 60
As Andrew said, both behaviors are correct as per ISO C99 since the only constraint is §6.5.2.4: 2 The result of the postfix ++ operator is the value of the operand. After the result is obtained, the value of the operand is incremented. (That is, the value 1 of the appropriate type is added to it.) See the discussions of additive operators and compound assignment for information on constraints, types, and conversions and the effects of operations on pointers. The side effect of updating the stored value of the operand shall occur between the previous and the next sequence point. and there is no sequence point within the expression x * n * --n. As a rule of thumb, in C/C++ do not mention more than once in an expression a variable whose value can change as part of the "execution" of the expression. -- Eric Botcazou