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); 
}

Output
2 2 1

Recommended Answers

All 6 Replies

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); 
}

Output
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

commented: Let the OP do some of their own work. -4

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 .

#include<stdio.h>
void main(void)
{
int x:1;
x=2;
printf("%d",x);
}

Result:
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 .

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.