开发者

How the compiler interprets preincrement/decrement and postincrement/decrement

开发者 https://www.devze.com 2023-03-16 13:39 出处:网络
When someone asks about the difference between post-increment/decrement and pre-increment/decrement, the response is usually that the prefix versions add one to the variable and return the new value o

When someone asks about the difference between post-increment/decrement and pre-increment/decrement, the response is usually that the prefix versions add one to the variable and return the new value of the variable whereas the postfix versions add one to the variable and return the old value.

While messing around, I found out that all of these lines are legal:

int i = 1;
++i;
++++++++++++++i;
(++++++++++++++i)++;
(++++++(++++(++i)))++;
------i;
--++++--++----++i;
i+=++++++++++++++i+i++-i--; 

But none of the following lines are legal:

i++++;
++i++;
--i--;

If I assume that the prefix versions return by reference, this all makes sense (even the last example because postfix has 开发者_StackOverflowhigher precedence than prefix).

Is the assumption/realization that the prefix versions return a reference and the postfix versions return a value correct? Are there any other subtle behavior differences that I don't know about for the pre/post inc/decrement operators?


All this is legal:

No, it isn't legal. Writing the variable more than once in that way is Undefined Behaviour. It's syntactically correct, and it'll compile, but it sure isn't legal.


In C++, the prefix increment/decrement expressions "return" lvalues and the postfix versions return rvalues. In C both forms return rvalues.

However, be aware that the behavior is undefined if you try to writing to a variable more than once between two sequence points. So the distinction doesn't really matter anyway.


One that comes to mind is the common coding error of using a variable at least twice in the same statement, with at least one instance applying a pre/post increment:

i = i++;


Is the assumption/realization that the prefix versions return a reference and the postfix versions return a value correct

No. Why would you assume that? It's a built in operator, and compiler can implement it as it wishes.

Your "legal" examples may compile, but will produce undefined behavior because you read and write into the same variable multiple times without a sequence point.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号