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
2------>2
3------>3
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
@sakharam
i didn't get this line from your answer
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.
64.3k questions
77.9k answers
244k comments
80.0k users