There is code:
#include <iostream>
class Int {
public:
Int() : x(0) {}
Int(int x_) : x(x_) {}
Int& operator=(const Int& b) {
std::cout << "= from " << x << " = " << b.x << std::endl;
x = b.x;
}
Int& operator+=(const Int& b) {
std::cout << "+= from " << x << " + " << b.x << std::endl;
x += b.x;
return *this;
}
Int& operator++() {
std::cout << "++ prefix " << x << std::endl;
++x;
return *this;
}
Int operator++(int) {
std::cout << "++ postfix " << x << std::endl;
Int result(*this);
++x;
return result;
}
private:
int x;
};
Int operator+(const Int& a, const Int& b) {
std::cout << "operator+" << std::endl;
Int result(a);
result += b;
return result;
}
int main() {
Int a(2), b(3), c(4), d;
d = ++a + b++ + ++c;
return 0;
}
Result:
++ prefix 4
++ postfix 3
++ prefix 2
operator+
+= from 3 + 3
operator+
+= from 6 + 5
= from 0 = 11
Why postfix operator isn’t executed before prefix operator (++ prefix 4) altough priority of postfix operator is higher than prefix operator?
This was compiled by g++.
The order of evaluation of the different operands is unspecified which means that the compiler is free to reorder the evaluation of the
++a,b++and++csubexpressions as it pleases. The precedence of the operators does not really have any impact in that example.It does have an effect if you try to write
++i++(whereiis anint) which will be grouped as++(i++)and it will fail to compile as the subexpressioni++is an rvalue and prefix increment requires an lvalue. If the precedence was reversed, then that expression would compile (and cause Undefined Behavior)