vijay
vijay

Reputation: 2034

Details of structure in C

I am newbie to C. I googled alot regarding the output of below code.But not much of help.

Here is the code:

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);
Output:
i: -1
j: -2
k: -3
l: -6

Can anyone explain why the outputs are so ? Thanks.

Upvotes: 4

Views: 179

Answers (2)

glglgl
glglgl

Reputation: 91049

Because your fields are not unsigned, thus they are signed.

If you have a signed field, its most significant bit dindicates negativeness. This implies that there is always one more negative value than positive - at least, in the implementation which you use, which seems to use two's complement numbers for negative.

If you put a 10 in a bit field of 4 bits, you have 1010, which is negative (-6).

If you put a 5 in a bit field of 3 bits, you have 101, which is negative (-3).

If you put a 2 in a bit field of 2 bits, you have 10, which is negative (-2).

If you put a 1 in a bit field of 1 bits, you have 1, which is negative (-1).

With

struct str
{
    unsigned int i: 1;
    unsigned int j: 2;
    unsigned int k: 3;
    unsigned int l: 4;
};

you should be able to achieve what you want.

Upvotes: 9

Puppy
Puppy

Reputation: 146940

You have used a bitfield but not accounted for the fact that the sign requires a bit to represent, narrowing the range to below the values you have assigned to them. You need to enlarge the storage for your fields if you want to store signed integers of that size.

Upvotes: 0

Related Questions