in Programming in C reopened by
1,206 views
2 votes
2 votes
#include <stdio.h>
struct p { unsigned int x : 1; unsigned int y : 1; };
int main() { struct p p; p.x = 1; p.y = 2; printf("%d\n", p.y); }
 

 

Why output is 0?
in Programming in C reopened by
1.2k views

2 Answers

2 votes
2 votes
Best answer

When colon is used like the following:

unsigned int y : 1, it means the data will be of size 1 bit

Also note that we have specified unsigned to range of y is 0 to 1

When  you assigned p.y=2, p.y was assigned 0 because

for y,

0------>0

1------>1

2------>0

3------>1

4------>0

Try changing unsigned int y:2, this will make it 2 bit length

0------>0

0------>0

1------>1

2------>2

3------>3

4------>0

 

Try to display warning and for a value larger than the range of that bit length, the warning "

warning: large integer implicitly truncated to unsigned type [-Woverflow]

" is dispayed.

Sources:

https://stackoverflow.com/questions/8564532/colon-in-c-struct-what-does-it-mean

https://stackoverflow.com/questions/2151305/gcc-warning-large-integer-implicitly-truncated-to-unsigned-type

Also if you were trying to set default values, if I am not wrong, you can't do that in C language. Correct me if I am wrong.

Also try to see what happens when data type is signed.

Also have a look at this: https://www.tutorialspoint.com/cprogramming/c_bit_fields.htm

selected by

4 Comments

@sakharam

i didn't get this line from your answer

Also if you were trying to set default values, if I am not wrong, you can't do that in C language. Correct me if I am wrong.

0
0
@Shaik Masthan I thought that the person who posted the question might be trying st set default vales to structure which means if the structure is not manually assigned values these values would be defined.

But this doesn't happen in C with Structures.
0
0
OK... But note that out of range value given, then value assigned is implementation defined...

i mean

unsigned int y:1

if you assign y= 2 ===> it will lead to implementation defined, may be which compiler you are using, that implemented as mod value.
1
1
Agreed!
0
0
0 votes
0 votes

unsigned int x : 1; unsigned int y : 1 enforces the size of x and y to be 1 bit ....

Thus y can have only two legal values 0 and 1. If we try to assign out of range value i.e  p.y = 2 the result would be implementation dependent........ 0 in this case as least significant 1 bit is taken.  If we try to assign p.y = 3 output would be 1.