5 Years
Discussion Span
Last Post by arindam31

Sure, write out 2,-6,5 in binary.

> int p:3;
Then take the right-most n-1 bits as the value, and the n'th as the sign bit.
The valid range of p for example is -4 to +3

struct marks{
int p:3;
int c:3;
int m:2;
void main()
struct marks s={2,-6,5};
printf("%d %d %d",s.p,s.c,s.m); 

2 2 1

since -6 in binary is 1010 and as c holds 3 bits of 1010 which is 010 equals to 2
and so on...
s.p = 2 = 0010 so p:3 = 010 = 2
s.c = -6 = 1010 so c:3 = 010 = 2
s.m = 5 = 0101 so m:2 = 01 = 1
hence the output is 2 2 1

Votes + Comments
Let the OP do some of their own work.

Thank you guys..that justified the output . But , it raised new doubts in my mind ............They are
1) when we declared here int p:3 , what kind of declaration is this ? When do we use this ? Are we trying to limit the variable input possibilities ?
I guess by your comments , it is a range from -4 to +3.
2)I tried it without structures but it didnt work . Why? See the code below .

void main(void)
int x:1;

prog.c:2: warning: return type of ‘main’ is not ‘int’
prog.c: In function ‘main’:
prog.c:4: error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘:’ token
prog.c:4: error: expected expression before ‘:’ token
prog.c:5: error: ‘x’ undeclared (first use in this function)
prog.c:5: error: (Each undeclared identifier is reported only once
prog.c:5: error: for each function it appears in.)

3) So Is it only possible while declaring structure variables ? Not in normal code ?


They're called bit-fields, and they're only allowed inside structures.

And yes, the number tells you how many bits are allocated to each small integer, from which it is easy to work out the valid range.


Thank you Salem..and all others ....I learn something new today and it was fun learning the concept. Thank you all .

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.