为什么以下代码的输出是-1和-2?

为什么下面代码的输出是-1和-2,它应该是1和2,对吧?

在以下结构的64位服务器大小上也是4字节,它应该是8字节对吗?

#include struct st { int a:1; int b:2; }; main() { struct st obj={1,2}; printf("a = %d\nb = %d\n",obj.a,obj.b); printf("Size of struct = %d\n",sizeof(obj)); } 

编译启用的所有警告,并阅读编译器所说的内容:

 Georgioss-MacBook-Pro:~ gsamaras$ gcc -Wall main.c main.c:7:1: warning: type specifier missing, defaults to 'int' [-Wimplicit-int] main() ^ main.c:9:26: warning: implicit truncation from 'int' to bitfield changes value from 2 to -2 [-Wbitfield-constant-conversion] struct st obj={1,2}; ^ main.c:11:40: warning: format specifies type 'int' but the argument has type 'unsigned long' [-Wformat] printf("Size of struct = %d\n",sizeof(obj)); ~~ ^~~~~~~~~~~ %lu 3 warnings generated. 

回想起那个

带符号的1位变量只能包含两个值,即-1和0

正如你在这个答案中看到的那样。

所以如果你改用这个结构:

 struct st { int a:2; int b:3; }; 

你会得到所需的输出。


这个答案也给出了一个很好的解释。