Why output of the below code is -1 and -2? [duplicate]

怎甘沉沦 提交于 2019-12-23 05:26:43

问题


Why output of the below code is -1 and -2, It should be 1 and 2, Right?

Also on a 64 bit server size of the below structure is 4 Bytes, It should be 8 Bytes right?

#include<stdio.h>
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));
}

回答1:


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.

Recall, that

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

as you can see in this answer.

So if you use this struct instead:

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

you will get the desired output.


This answer gives a nice explanation as well.



来源:https://stackoverflow.com/questions/43889846/why-output-of-the-below-code-is-1-and-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!