为什么A =(A + B) - (B = A)用于交换两个整数一个坏的选择? [英] Why is a = (a+b) - (b=a) a bad choice for swapping two integers?

查看:157
本文介绍了为什么A =(A + B) - (B = A)用于交换两个整数一个坏的选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一头栽进这个code用于交换两个整数,而无需使用一个临时变量或使用位运算符。

I stumbled into this code for swapping two integers without using a temporary variable or the use of bitwise operators.

int main(){

    int a=2,b=3;
    printf("a=%d,b=%d",a,b);
    a=(a+b)-(b=a);
    printf("\na=%d,b=%d",a,b);
    return 0;
}

但我认为这code在交换声明 A =(A + B)已未定义的行为 - (B = A); ,因为它不含有任何的序列点以确定评估的顺序。

But I think this code has undefined behavior in the swap statement a = (a+b) - (b=a); as it does not contain any sequence points to determine the order of evaluation.

我的问题是:这是一个可以接受的解决方案,以交换两个整数

推荐答案

没有。这是不能接受的。这code调用 未定义行为 。这是因为的操作B 中没有定义。在EX pression

No. This is not acceptable. This code invokes Undefined behavior. This is because of the operation on b is not defined. In the expression

a=(a+b)-(b=a);  

是否 B 被修改第一或它的价值得到了前pression(用现在还不能确定 A + B )因为缺乏序列点的。结果
看看有什么标准syas:

it is not certain whether b gets modified first or its value gets used in the expression (a+b) because of the lack of the sequence point.
See what standard syas:

如果一个标物体上的副作用是相对于同一标量对象上或任一不同的副作用unsequenced的使用相同的标量的值的值计算
  对象
,其行为是不确定的。 如果有多个允许的排序
  SUBEX $一名前pression的对$ pssions,其行为如果这种unsequenced一边是未定义
  效果任何orderings.84发生)
<分> 1 。

If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings.84)1.

C-FAQ - 3.8 这的回答的顺序点和未定义行为的更详细的解释。

Read C-faq- 3.8 and this answer for more detailed explanation of sequence point and undefined behavior.

<分> 1。重点是我的。

这篇关于为什么A =(A + B) - (B = A)用于交换两个整数一个坏的选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆