Here is the version and system info:
% g++ -v
Reading specs from /usr/lib/gcc/i386-redhat-linux/3.4.5/specs
Configured with: ../configure --prefix=/usr --mandir=/usr/share/man --infodir=/usr/share/info --enable-shared --enable-threads=posix --disable-checking --with-system-zlib --enable-__cxa_atexit --disable-libunwind-exceptions --enable-java-awt=gtk --host=i386-redhat-linux
Thread model: posix
gcc version 3.4.5 20051201 (Red Hat 3.4.5-2)
Here is the output from the test program (which is included below)
% g++ -o associativityTest -O3 associativityTest.cpp
neg_50 = -50
% g++ -o associativityTest associativityTest.cpp
neg_50 = 50
You can see the different answers above, as a result of compiling with and without optimization. The answer of -50 is correct, based on the left to right associativity of the * operator.
Here is the test file associativityTest.cpp:
using namespace std;
explicit Int(int value)
_value *= -1;
Int operator*(Int right)
Int operator*(Int I, int i)
Int operator*(int i, Int I)
Int neg_50 = (five * 2 * five.neg());
cout << "neg_50 = " << neg_50.value() << endl;
(five * 2 * five.neg());
This is equivlant to:
(five * 2) * (five.neg())
but the C and C++ standard do not specify which expression is evulated first.
In that (five * 2) might be evulated first or five.neg(). five.neg() has a side effect of changing five (_value *= -1;) which makes the above statement undefined as five is accessed and written to without a sequence point inbetween.
And it makes it a duplicate of PR 11751.
*** This bug has been marked as a duplicate of 11751 ***