0

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));
}
gsamaras
  • 71,951
  • 46
  • 188
  • 305
Chirag
  • 607
  • 1
  • 6
  • 17

1 Answers1

3

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.

Community
  • 1
  • 1
gsamaras
  • 71,951
  • 46
  • 188
  • 305