且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2022-05-10 04:01:51

在启用所有警告的情况下编译,并阅读您的编译器所说的内容:

Compile with all the warnings enabled, and read what your compiler says:

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

a signed 1 bit variable can hold only two values, -1 and 0

正如您在此答案中所见.

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

So if you use this struct instead:

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

您将获得所需的输出.

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

This answer gives a nice explanation as well.