Search code examples
c++coperatorspre-incrementoperator-precedence

Multiple preincrement operations on a variable in C++(C ?)


Why does the following compile in C++?

int phew = 53;
++++++++++phew ;

The same code fails in C, why?


Solution

  • That is because in C++ pre-increment operator returns an lvalue and it requires its operand to be an lvalue.

    ++++++++++phew ; in interpreted as ++(++(++(++(++phew))))

    However your code invokes Undefined Behaviour because you are trying to modify the value of phew more than once between two sequence points.

    In C, pre-increment operator returns an rvalue and requires its operand to be an lvalue. So your code doesn't compile in C mode.