Java 赋值运算符行为与 C++
Java assignment operator behavior vs C++
这发生在我处理 'Cracking the Coding interview' 问题时:
Write a function to swap a number in place (that is, without temporary variables)
我决定在 Java 中写下我的解决方案(因为我计划在实习面试中使用 Java。)
我想出了一个我几乎确信是正确答案的解决方案(因为我是在一行中完成的):
public static void main(String args[]) {
int a = 5;
int b = 7;
a = b - a + (b = a);
System.out.println("a: " + a + " b: " + b);
}
果然,这段代码执行了想要的结果。 a == 7
和 b == 5
.
现在是有趣的部分。
此代码不会 运行 在 C++ 中,本书后面也没有此解决方案。
所以我的问题是:为什么我的解决方案有效?我假设 Java 做事与其他语言不同?
查看Java Language Specification, section 15.7 (Evaluation Order):
The Java programming language guarantees that the operands of
operators appear to be evaluated in a specific evaluation order,
namely, from left to right.
所以在 Java 中评估顺序是明确定义的并且符合您的期望。
C++ 规范不提供这样的保证;事实上,它是未定义的行为,所以程序实际上可以做任何事情。
引用 cppreference,注意不存在对算术运算符的操作数排序的排序规则:
If a side effect on a scalar object is unsequenced relative to a value
computation using the value of the same scalar object, the behavior is
undefined.
这发生在我处理 'Cracking the Coding interview' 问题时:
Write a function to swap a number in place (that is, without temporary variables)
我决定在 Java 中写下我的解决方案(因为我计划在实习面试中使用 Java。)
我想出了一个我几乎确信是正确答案的解决方案(因为我是在一行中完成的):
public static void main(String args[]) {
int a = 5;
int b = 7;
a = b - a + (b = a);
System.out.println("a: " + a + " b: " + b);
}
果然,这段代码执行了想要的结果。 a == 7
和 b == 5
.
现在是有趣的部分。
此代码不会 运行 在 C++ 中,本书后面也没有此解决方案。
所以我的问题是:为什么我的解决方案有效?我假设 Java 做事与其他语言不同?
查看Java Language Specification, section 15.7 (Evaluation Order):
The Java programming language guarantees that the operands of operators appear to be evaluated in a specific evaluation order, namely, from left to right.
所以在 Java 中评估顺序是明确定义的并且符合您的期望。
C++ 规范不提供这样的保证;事实上,它是未定义的行为,所以程序实际上可以做任何事情。
引用 cppreference,注意不存在对算术运算符的操作数排序的排序规则:
If a side effect on a scalar object is unsequenced relative to a value computation using the value of the same scalar object, the behavior is undefined.