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
% ./associativityTest
neg_50 = -50
% g++ -o associativityTest associativityTest.cpp
% ./associativityTest
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:

#include <iostream>

using namespace std;

class Int
{
public:
  explicit Int(int value)
    : _value(value)
  {
  }

  Int neg()
  {
    _value *= -1;
    return *this;
  }

  int value()
  {
    return _value;
  }

  Int operator*(Int right)
  {
    return Int(_value*right._value);
  }

private:
  int _value;
};

Int operator*(Int I, int i)
{
  return I*Int(i);
}

Int operator*(int i, Int I)
{
  return I*i;
}

int main()
{
  Int five(5);

  Int neg_50 = (five * 2 * five.neg());

  cout << "neg_50 = " << neg_50.value() << endl;
}


-- 
           Summary: associativity of * operator incorrect when compiled
                    without optimization
           Product: gcc
           Version: 3.4.5
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c++
        AssignedTo: unassigned at gcc dot gnu dot org
        ReportedBy: mike dot clarkson at spacedev dot com


http://gcc.gnu.org/bugzilla/show_bug.cgi?id=27344

Reply via email to