Inside the struct definition, the line int p:3;
defines p
as a bit field with 3 bits. Additionally, since the type on the left side (int
) is signed, that means p
will be a signed bit field. So it can hold values from -4 to 3. It probably uses two's complement on your computer, so the correspondence between bits and values is:
Bits of p |
Value |
100 |
-4 |
101 |
-3 |
110 |
-2 |
111 |
-1 |
000 |
0 |
001 |
1 |
010 |
2 |
011 |
3 |
The line struct marks s={2,-6,5};
is basically equivalent to the following code (although sometimes there is a difference in warnings/errors emitted by the compiler):
struct marks s;
s.p = 2;
s.c = -6;
s.m = 5;
Since c
and m
do not have enough bits to hold the values being assigned to them here, your implementation will have to modify the values before storing them in those variables. Usually this is done by truncating the high bits. So -6 (11111010 in binary) becomes 2 (010) when we cram it into a 3-bit field, while 5 (00000101) becomes 1 (01) when we cram it into a 2-bit field.