Quantcast
Viewing all articles
Browse latest Browse all 22029

Is it possible to write a _Static_assert in GCC/GNU C that would verify the layout of bit fields in memory at compile time?

Suppose that I have the following definitions:

#include <stdbool.h>#include <stdint.h>#define ASSERT(cond) _Static_assert(cond, #cond)typedef union {    struct {        bool bit0:1;        bool bit1:1;        bool bit2:1;        bool bit3:1;        bool bit4:1;        bool bit5:1;        bool bit6:1;        bool bit7:1;    };    uint8_t bits;} byte;ASSERT(sizeof(byte) == sizeof(uint8_t));

Is it possible to write a code, such as

#include <assert.h>// ...    assert(((byte) { .bit0 = 1 }).bits == 0b00000001);    assert(((byte) { .bit1 = 1 }).bits == 0b00000010);    assert(((byte) { .bit2 = 1 }).bits == 0b00000100);    assert(((byte) { .bit3 = 1 }).bits == 0b00001000);    assert(((byte) { .bit4 = 1 }).bits == 0b00010000);    assert(((byte) { .bit5 = 1 }).bits == 0b00100000);    assert(((byte) { .bit6 = 1 }).bits == 0b01000000);    assert(((byte) { .bit7 = 1 }).bits == 0b10000000);// ...

that would cause a compile-time failure if the above conditions weren't satisfied?

(When I try to place the conditions in the ASSERT macro, the compiler complains that expression in static assertion is not constant, which of course makes perfect sense)

The solution is allowed to use the GNU extensions to the C language.


Viewing all articles
Browse latest Browse all 22029

Trending Articles