Why the following code snippet output is 0 6 20 42 72 110
not 0 4 16 36 64 100
?
for(int i=0;i<11;i++){
cout<< i * i++ <<" ";
}
According to C++ Operator Precedence Suffix/postfix increment and decrement has higher precedence than multiplication which means that "i" will be incremented before multiplication.
Edit:
According to Problem with operator precedence question, they said that Operator precedence does not in any way determine the order in which the operators are executed. Operator precedence only defines the grouping between operators and their operands, So how can cout<< i * i++ <<" ";
will be grouped?
The order of evaluation of the operands in i * i++
is not guaranteed. You expect it to be left-to-right but your compiler is implementing it right-to-left. This means the increment happens before it evaluates the left-hand side i
, meaning it prints 1 * 0
, 3 * 2
, 5 * 4
etc.