...
This noncompliant code uses the assert() macro to assert a property concerning a memory-mapped structure that is essential for the code to behave correctly.
| Code Block | ||||
|---|---|---|---|---|
| ||||
struct timer {
uint8_t MODE;
uint32_t DATA;
uint32_t COUNT;
};
int func(void) {
assert(offsetof(timer, DATA) == 4);
}
|
...
For assertions involving only constant expressions, some implementations allow the use of a preprocessor conditional statement, as in this example:
| Code Block | ||||
|---|---|---|---|---|
| ||||
struct timer {
uint8_t MODE;
uint32_t DATA;
uint32_t COUNT;
};
#if (offsetof(timer, DATA) != 4)
#error "DATA must be at offset 4"
#endif
|
...
This portable compliant solution uses static_assert.
| Code Block | ||||
|---|---|---|---|---|
| ||||
struct timer {
uint8_t MODE;
uint32_t DATA;
uint32_t COUNT;
};
static_assert(offsetof(struct timer, DATA) == 4, "DATA must be at offset 4");
|
...