Search code examples
cbit-fields

Why printing -1 for this code, I supposed it to be 1 when bit-field is set to 1?


#include<stdio.h>  
int main()  
{  
    struct byte  
    {  
        int one:1;  
    };

    struct byte var = {1};  // statement A
    printf("%d", var.one);  
    return 0;  
}  

Here, what I suppose is that we've limited the bit-memory of integer variable 'one' to 1 only ie; it can only store 0 and 1 and at 'statement A' we've initialized this variable with '1' which should've been fine as 'one' can still hold a bit in its memory but it's printing -1 on console ! Any help ?


Solution

  • It is implementation-defined whether a bit field defined with type int is equivalent to signed int or unsigned int. (This applies only to bit fields; otherwise int is exactly the same as signed int.)

    If int one:1; is signed (as it appears to be in your implementation), then that single bit is the sign bit, and the only possible values are 0 and -1. The value 1 that you've used to initialize it, since it's out of range, is implicitly converted to -1. (Actually the result of the conversion is implementation-defined.)

    Change the declaration to:

    unsigned int one:1;
    

    and it can have values 0 and 1. Bit fields should usually be explicitly unsigned unless you really need them to be signed -- and in that case you should use signed int rather than int.