Monday, November 11, 2019

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?


Answer



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.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...