I have written some code with bit fields that I thought should work, but it seems like GCC disagrees. Did I miss something or did I actually find a bug in GCC?
After simplifying my code, the testcase is quite simple. I'm assigning the integer literal 1
to a bitfield that has a size of one bit:
typedef struct bitfield
{
int bit : 1;
} bitfield;
bitfield test()
{
bitfield field = {1};
return field;
}
If I compile this with GCC 6.2.1 (same with 5.4.0), I get the following warning (with -pedantic):
gcc -fPIC test.c -pedantic -shared
test.c: In function ‘test’:
test.c:8:23: warning: overflow in implicit constant conversion [-Woverflow]
bitfield field = {1};
^
The strange thing is: When I replace -pedantic with -Woverflow, the warning disappears.
I don't get any warnings with clang.
In above student structure size of the structure without bit field is size of (StdId) + size of (Age) = 8 bytes + 8 Bytes = 16 bytes. After using bit fields to its members, it is 8 bits + 4 bits = 12 bits = 1.5 bytes which is very much less. Hence we can save lot of memory.
Bit fields can be used to reduce memory consumption when a program requires a number of integer variables which always will have low values. For example, in many systems storing an integer value requires two bytes (16-bits) of memory; sometimes the values to be stored actually need only one or two bits.
In programming terminology, a bit field is a data structure that allows the programmer to allocate memory to structures and unions in bits in order to utilize computer memory in an efficient manner. Since structures and unions are user-defined data types in C, the user has an idea of how much memory will they occupy.
You cannot store a float value in a bit-field structure. Floats have to adhere to a specific standard (IEEE 754) that specifies a representation. These representations are for 32 and 64 bits on x86. Therefore a bit field wouldn't have the necessary space to properly represent a floating point value..
Use unsigned int
for this bit field. A 1-bit signed number can only hold 0
and -1
.
typedef struct bitfield
{
unsigned int bit : 1;
} bitfield;
is this bit field of size one actually overflowing when assigning 1?
Maybe. It is implementation defined.
This is a place in C where int
and signed int/signed
may differ.
unsigned int bit : 1;
can hold the value 0 or 1.
Assuming 2's complement machine ...
signed int bit : 1;
can hold the value 0 or -1signed bit : 1;
can hold the value 0 or -1
int bit : 1;
can hold the value 0 or 1 or 0 or -1
Each of the comma-separated multisets (
int, signed, or signed int
) designates the same type, except that for bitfields, it is implementation-defined whether the specifierint
designates the same type assigned int
or the same type asunsigned int
. C11 dr §6.7.2 5
Using unsigned
removes ambiguities.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With