c - 在不使用 C 中的第三个变量的情况下交换两个变量的值?

标签 c expression operator-precedence sequence-points

我找到了以下代码片段:

#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);
    ~   ^

据我所知默认情况下。您可以使用 -Wallgcc 收到类似的警告。

有几个 SO 问题涉及如何在没有临时文件的情况下进行交换,例如 Swapping two variable value without using 3rd variable .

关于c - 在不使用 C 中的第三个变量的情况下交换两个变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24812660/

相关文章:

java - Spring:如何在投影中使用SpEL表达式

c++ - 当通过指针递增成员 int 时,c++ 与 -> 的运算符优先级如何工作?

c++ - 传递函数参数的求值顺序 - F1( int F2( int& x ), int x ) 的操作顺序

c - 为什么我的程序在将内存分配给双指针 C 时会产生段错误

c# - 二进制搜索算法的扩展,用于查找要在数组中搜索的键值的第一个和最后一个索引

c - 为什么这个函数在完成递归运行后返回整数 17?

linq - TableServiceContext和动态查询

sql - 字符串是否可以由一组字母组成的正则表达式

c++ - 为什么 (*callback)() 有效,而 *callback() 或 *callback 在 C++ 中不起作用

c - 需要帮助结合两个C代码