For an implementation that packs f0
and f1
into the same byte, is the program below defined?
struct S0 {
unsigned f0:4;
signed f1:4;
} l_62;
int main (void) {
(l_62.f0 = 0) + (l_62.f1 = 0);
return 0;
}
I am interested in the answer for C99 and for C11 if there is reason to think that it is different there.
In C99, all I found was 6.5:2:
Between the previous and next sequence point an object shall have its stored value modified at most once by the evaluation of an expression. [...]
It is not clear for me what consequences this paragraph has on the program above.
Based on a large number of randomized tests, most compilers appear to generate code where the two assignments do not interfere.
A bit field is a data structure that consists of one or more adjacent bits which have been allocated for specific purposes, so that any single bit or group of bits within the structure can be set or inspected.
Because bit-fields do not necessarily begin at the beginning of a byte, address of a bit-field cannot be taken. Pointers and non-const references to bit-fields are not possible.
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.
Both C and C++ allow integer members to be stored into memory spaces smaller than the compiler would ordinarily allow. These space-saving structure members are called bit fields, and their width in bits can be explicitly declared.
C11 considers adjacent named bit fields to be part of the same memory location. Such bit fields are not guaranteed to be updated atomically, in other words if one update is not sequenced explicitly before the other the behavior is undefined. 3.14 memory location
then also has a detailed explanation of when two fields can be considered being in different memory locations, thus updates to them can be considered independently.
If you would modify your structure
struct S0 {
unsigned f0:4;
int :0;
signed f1:4;
} l_62;
such that there is this bizarre "memory location separator" between the two bit fields, your code would be guaranteed to be fine.
For C99 the case seems to be more complicated, there is not such a detailed concept of memory location. In a recent discussion on the linux kernel mailing list there was a claim that generally for all pairs of bit fields there would be a guarantee of atomicity when updating any of them. The starting point of that discussion was a case where gcc polluted a non-bit field neighboring a bit field in an unexpected way leading to spurious crashes.
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