Can someone explain me why do we get the following output?

176 views Asked by At
#include<stdio.h>
int main(void)
{
struct str
{
    int i: 1;
    int j: 2;
    int k: 3;
    int l: 4;
};

struct str s;

s.i = 1;
s.j = 2;
s.k = 5;
s.l = 10;

printf(" i: %d \n j: %d \n k: %d \n l: %d \n", s.i, s.j, s.k, s.l);

getchar();
return 0;
}

Output Given in the website:

i: 1
j: 2
k: 5
l: 10

I got

i :-1 
j : -2 
k : -3
l : -6

I don't understand what is bit field. And can someone tell me what's going on in this code here?

1

There are 1 answers

0
Weather Vane On

If you write down a column of the possible bit patterns for each width of those signed variables, with the decimal equivalent next to them, you will soon see why you get those results. Assuming 2's complement respresentation, a 1-bit signed variable has two possible values: -1 and 0. A 2-bit signed variable stores values in the range -2 to 1 and so on.

Bin Dec     Bin Dec     Bin Dec
011  3      01   1      0    0
010  2      00   0      1   -1
001  1      11  -1
000  0      10  -2
111 -1
110 -2
101 -3
100 -4

In your case of s.i = 1; the int value 1 is binary 1, and as you can see for the 1-bit variable, this has the value -1.

In your case of s.j = 2; the int value 2 is binary 10, and as you can see for the 2-bit variable, this has the value -2.

In your case of s.k = 5; the int value 5 is binary 101, and as you can see for the 3-bit variable, this has the value -3.

However this is just an explanation of what might be happening, because it is implementation-defined behaviour to assign a value which is outside of the representable range of a signed integer.

I will leave you to work out the 4-bit one for yourself. With s.l = 10; that value is also outside of the range of the 4-bit signed variable, which is -8 to 7.