1

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?

Ahmed Farag
  • 83
  • 1
  • 7
  • The cppreference page you linked explains that precedence is orthogonal to order of evaluation and gives a link to [the page with the OOE rules](http://en.cppreference.com/w/cpp/language/eval_order). In fact, it has a very similar example, with addition instead of multiplication. – chris Nov 10 '17 at 15:05
  • Unless this is C++17, `i * i++` is undefined and your program not a C++ program. – molbdnilo Nov 10 '17 at 15:09
  • real dupe: [Operator Precedence vs Order of Evaluation](https://stackoverflow.com/questions/5473107/operator-precedence-vs-order-of-evaluation) – underscore_d Nov 10 '17 at 15:12
  • @molbdnilo, It's still undefined in C++17. – chris Nov 10 '17 at 15:14
  • @molbdnilo Why this snippet is't c++, This is the complete program `#include using namespace std; int main(){ for(int i=0;i<11;i++){ cout<< i * i++ <<" "; } return 0; }` – Ahmed Farag Nov 10 '17 at 15:21

1 Answers1

0

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188