如果我想给变量赋新值并检查新值是否与旧值相同,我会倾向于避免使用临时变量。我可以做这样的事情吗:
if (oldval == (oldval = new_value()))
{
... do something
}
?
这种行为是明确定义的还是评估优先语言或编译器相关?我可以试试看结果,但不能保证它也能在其他系统上运行。我是用 C++ 做的,所以这是我最感兴趣的语言,但如果行为在其他语言中是一致的(或不一致的),我想知道。
谢谢!
最佳答案
==
的操作数的求值顺序未定义(我假设 ==
未重载)。无法保证 oldval
会先求值还是 oldval = new_value()
会先求值。在这种情况下,行为是未定义。
避免编写这样的表达式来访问变量的值并在表达式的其他地方修改该变量。
注意:只有运算符 、
、&&
、||
和 ?:
保证操作数计算从左到右进行。所以,存在sequence point :
- Between evaluation of the left and right operands of the
&&
(logical AND),||
(logical OR) (as part of short-circuit evaluation), and comma operators.- Between the evaluation of the first operand of the ternary "question-mark" operator and the second or third operand.
关于c++ - 这种情况会导致什么结果?它是定义的还是依赖于编译器的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24047447/