我找到了以下代码片段:
#include <stdio.h>
int main(void) {
int x=10,y=15;
x=x+y-(y=x);
printf("x=%d y=%d",x,y);
return 0;
}
It actually swaps the variables
谁能解释一下代码是如何交换变量的?
我以为括号会先执行然后表达式导致
x=x+y-y;
最佳答案
此算法不起作用,因为它在此行调用了未定义的行为:
x=x+y-(y=x);
^ ^
您正在修改 y
并根据 C99 标准草案的 6.5
部分在同一序列点内使用它的值:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression.72) Furthermore, the prior value shall be read only to determine the value to be stored.73)
由于未指定子表达式的求值顺序,因此还存在未指定行为的问题:
The grouping of operators and operands is indicated by the syntax.74) Except as specified later (for the function-call (), &&, ||, ?:, and comma operators), the order of evaluation of subexpressions and the order in which side effects take place are both unspecified.
在这种情况下,如果您使用 clang
,它会提供以下警告:
warning: unsequenced modification and access to 'y' [-Wunsequenced]
x=x+y-(y=x);
~ ^
据我所知默认情况下。您可以使用 -Wall
从 gcc
收到类似的警告。
有几个 SO 问题涉及如何在没有临时文件的情况下进行交换,例如 Swapping two variable value without using 3rd variable .
关于c - 在不使用 C 中的第三个变量的情况下交换两个变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24812660/