相关疑难解决方法(0)

为什么这些构造使用前后增量未定义的行为?

#include <stdio.h>

int main(void)
{
   int i = 0;
   i = i++ + ++i;
   printf("%d\n", i); // 3

   i = 1;
   i = (i++);
   printf("%d\n", i); // 2 Should be 1, no ?

   volatile int u = 0;
   u = u++ + ++u;
   printf("%d\n", u); // 1

   u = 1;
   u = (u++);
   printf("%d\n", u); // 2 Should also be one, no ?

   register int v = 0;
   v = v++ + ++v;
   printf("%d\n", v); // 3 (Should be the …
Run Code Online (Sandbox Code Playgroud)

c increment operator-precedence undefined-behavior sequence-points

793
推荐指数
13
解决办法
7万
查看次数

为什么a =(a + b) - (b = a)是交换两个整数的不错选择?

我偶然发现了这个代码,用于交换两个整数而不使用临时变量或使用按位运算符.

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;
}
Run Code Online (Sandbox Code Playgroud)

但我认为这段代码在swap语句中有未定义的行为,a = (a+b) - (b=a);因为它不包含任何序列点来确定评估的顺序.

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

c c++ swap undefined-behavior sequence-points

58
推荐指数
9
解决办法
7681
查看次数

什么时候在 c 中计算表达式中括号内的赋值运算符?

所以我在 quora 文章中遇到了这段代码来交换两个数字。

a = a + b - (b = a);
Run Code Online (Sandbox Code Playgroud)

我试过了,效果很好。但是既然b = a是在括号中,不应该首先为 b 值分配 a 的值吗?整个事情应该成为a + a - a 一个保留其价值的东西?

我试过a = b + (b = a);a = 5 b = 10,最后我得到了一个 = 10。看到这里我猜它被评估为a = a + a

为什么会出现这种异常?

c operator-precedence parentheses undefined-behavior assignment-operator

2
推荐指数
1
解决办法
627
查看次数