reopened by
1,223 views

2 Answers

Best answer
2 votes
2 votes

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

Related questions

0 votes
0 votes
0 answers
1
Garrett McClure asked Sep 13, 2017
314 views
Write one or more C statements that clears (i.e., sets to 0) bits 11 and 12 of the variable "x" without disturbing the other bits using bit-level C operators. The variabl...
0 votes
0 votes
2 answers
2
Debargha Mitra Roy asked Apr 10
122 views
What is the output of the below code?#include <stdio.h void main() { static int var = 5; printf("%d ", var ); if (var) main(); }a. 1 2 3 4 5b. 1c. 5 4 3 2 1d. Error
3 votes
3 votes
3 answers
3
Laxman Ghanchi asked May 19, 2023
1,177 views
#include<stdio.h void print(int n) { printf("Hello "); if(n++ == 0) return ; print(n); n++; } int main() { void print(); print(-4); }How many times printf execute?? And H...