Small and pretty nasty problem I've seen several days ago, asked to my friend on interview.
The initial interview question was: "What will be the output of the following code?"
int i = 2;
i = i++ + i++;
The correct answer is ((2 + 2) + 1) + 1 = 6, i.e. post-increment is applied twice before assignment, but after addition.
Then I wanted to create a simple class carrying one integer and overload operator+() and operator++(int) to see in logs the exact order, in which operators will be executed.
This is what I got:
class A
{
public:
A(int _data) : data(_data) { }
A &operator=(const A& _rhs)
{
data = _rhs.data;
cout<<" -- assign: "<<data<<endl;
}
A operator++(int _unused)
{
A _tmp = data;
data++;
cout<<" -- post-increment: "<<data<<endl;
return _tmp;
}
A operator+(const A &_rhs)
{
A _tmp = data + _rhs.data;
cout<<" -- addition: "<<data<<"+"<<_rhs.data<<endl;
return _tmp;
}
inline operator int() const { return data; }
private:
int data;
};
The result was pretty discouraging:
-- post-increment: 3
-- post-increment: 4
-- addition: 3+2
-- assign: 5
For less sophisticated constructions, such as (A _dt2 = a++; ), it acts as it should, but the order of operators execution is not as for integral types.
It might be compiler specific problem, I guess:
$ gcc --version
gcc (Ubuntu 4.4.3-4ubuntu5) 4.4.3
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
So, I'm a bit lost :)