看这段代码:
#include <stdio.h>
#include <stdlib.h>
int main(){
int a = -1;
int b = 0xfc; // = 252
b+=a && a++;
printf("%d %d\n", a, b);
}
我认为应该是的输出是:
0 251
实际上,真正的输出是:
0 253
但为什么?&& 的结合性是从左到右,所以
- b = b - 1(a)(b 应该是 251)
- 左边是真的,所以:a++ (a = 0)
我的假设有问题,有人可以向我解释一下吗?
如果可以帮助 gdb 的输出(带有 a 和 b 的观察点):
Old value = 0
New value = -1
main () at test.c:7
7 int b = 0xfc;
(gdb) c
Continuing.
Hardware watchpoint 2: b
Old value = 0
New value = 252
main () at test.c:8
8 b+=a && a++;
(gdb) c
Continuing.
Hardware watchpoint 3: a
Old value = -1
New value = 0
0x0000555555555172 in main () at test.c:8
8 b+=a && a++;
(gdb) c
Continuing.
Hardware watchpoint 2: b
Old value = 252
New value = 253
main () at test.c:9
9 printf("%d %d\n", a, b);