Struct - Explain the output:

前端 未结 3 1993
一向
一向 2021-01-20 21:53

I have the following C code.

struct values{
  int a:3;
  int b:3;
  int c:2;
};

void main(){
  struct values v={2,-6,5};
  printf(\"%d %d %d\",v.a,v.b,v.c);         


        
3条回答
  •  太阳男子
    2021-01-20 22:41

    No. Output is 2 2 1.

    The C compiler converts the values to Binary, and stores in the memory.

    Binary value of 2 : 00000010

    Binary value of -6: 11111010 (11111001+1)

    Binary value of 5 : 00000101

    While storing in memory:

    For 2, 010 will be stored.

    For -6, 010 will be stored.

    For 5, 01 will be stored.

    When you access these variables from your main method, for v.a "010" will be returned, here left most bit is for sign.

    So v.a is 2. Similarly v.b is 2 and v.c is 1.

    Hope it helps.

提交回复
热议问题