I have written the following simple C++ program to output the powers of a number input by the user to indices 2, 3, and 4:
int a = 0;
cin >> a;
int a2 = a * a;
cout << "\n" << a2 << "\n" << (a2 *= a) << "\n" << (a2 *= a) << "\n";
return 0;
The output for a = 2
was
16
16
16
Can anybody explain why that is?
Can anybody explain why that is?
This is because you are using a C++ compiler that supports C++14, or earlier.
Before C++17 the evaluation order for the following expression is not specified by the C++ standard:
cout << "\n" << a2 << "\n" << (a2 *= a) << "\n" << (a2 *= a) << "\n";
C++14, and earlier, allows the C++ compiler to implement any evaluation order for this expression. Before C++17 it was allowed (but not required), for both a2 *= a
expressions to be evaluated first, setting a2
to 16
, in the end, which gets cout
ed three times.
As a general rule of thumb: unless the evaluation order is specified it is entirely up to your compiler to evaluate the expression in any order. For example, with int x=foo() + bar();
either foo()
or bar()
may be called first, followed by the other one. The order of evaluation of +
's operands is not specified by the C++ standard. Your expression using <<
operators is the same thing.
Before C++17 the above statement may produce different output with different C++ compilers, depending on which evaluation order they chose. It is entirely up to them.
Starting with C++17 the evaluation order here is specified, and you will get the intuitively expected results.