简体   繁体   中英

Bit-fields and sequence points

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.

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.

The assignment here is to the struct members. The fact that they happen to share the same storage should have no effect on the logic. You have not, in fact, actually made an assignment to the same thing.

Of course, I am not a language lawyer.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM