编译器如何解释前递增/递减和后递增/递减
当有人问后自增/自减和预自增/自减之间的区别时,通常的回答是前缀版本给变量加一并返回变量的新值,而后缀版本给变量加一并返回返回旧值。
在闲逛时,我发现所有这些行都是合法的:
int i = 1;
++i;
++++++++++++++i;
(++++++++++++++i)++;
(++++++(++++(++i)))++;
------i;
--++++--++----++i;
i+=++++++++++++++i+i++-i--;
但以下行都不合法:
i++++;
++i++;
--i--;
如果我假设前缀版本通过引用返回,这一切都是有道理的(即使是最后一个例子,因为后缀的优先级高于前缀)。
前缀版本返回引用而后缀版本返回值的假设/实现是否正确?对于前/后递增/递减运算符,是否还有其他我不知道的细微行为差异?
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 higher 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不,这是不合法的。以这种方式多次写入变量是未定义行为。它在语法上是正确的,并且可以编译,但它肯定不合法。
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.
在 C++ 中,前缀递增/递减表达式“返回”左值,后缀版本返回右值。在 C 中,两种形式都返回右值。
但是,请注意,如果您尝试在两个序列点之间多次写入变量,则行为是未定义的。所以无论如何,区别并不重要。
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:
否。您为什么会这样认为?它是一个内置运算符,编译器可以按照自己的意愿实现它。
您的“合法”示例可能会编译,但会产生未定义的行为,因为您在没有序列点的情况下多次读取和写入同一变量。
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.