I saw the below code in this Quora post:
#include <stdio.h>
struct mystruct { int enabled:1; };
int main()
{
struct mystruct s;
s.enabled = 1;
if(s.enabled == 1)
printf("Is enabled\n"); // --> we think this to be printed
else
printf("Is disabled !!\n");
}
In both C & C++, the output of the code is unexpected,
Is disabled !!
Though the "sign bit" related explanation is given in that post, I am unable to understand, how it is possible that we set something and then it doesn't reflect as it is.
Can someone give a more elaborate explanation?
Note: Both the tags c & c++ are required, because their standards slightly differ for describing the bit-fields. See answers for C specification and C++ specification.
As per the C++ standard n4713, a very similar code snippet is provided. The type used is
BOOL
(custom), but it can apply to any type.At 1st glance, the bold part appears open for interpretation. However, the correct intent becomes clear when the
enum BOOL
is derived from theint
.With above code it gives a warning without
-Wall -pedantic
:The output is:
If
enum BOOL : int
is made simpleenum BOOL
, then the output is as the above standard pasage specifies:Hence, it can be concluded, also as few other answers have, that
int
type is not big enough to store value "1" in just a single bit bit-field.