...
Code Block | ||||
---|---|---|---|---|
| ||||
struct timer { uint8_tunsigned char MODE; unsigned uint32_tint DATA; unsigned uint32_tint COUNT; }; int func(void) { assert(offsetofsizeof(struct timer, DATA) == 4 sizeof(unsigned char) + sizeof(unsigned int) + sizeof(unsigned int)); } |
Although the use of the runtime assertion is better than nothing, it needs to be placed in a function and executed. This means that it is usually far away from the definition of the actual structure to which it refers. The diagnostic occurs only at runtime and only if the code path containing the assertion is executed.
...
Code Block | ||||
---|---|---|---|---|
| ||||
struct timer { unsigned uint8_tchar MODE; uint32_tunsigned int DATA; unsigned uint32_tint COUNT; }; #if (offsetofsizeof(timer, DATA) != 4struct timer) == sizeof(unsigned char) + sizeof(unsigned int) + sizeof(unsigned int)) #error "DATAStructure must benot athave offsetany 4padding" #endif |
Using #error
directives allows for clear diagnostic messages. Because this approach evaluates assertions at compile time, there is no runtime penalty.
...
Code Block | ||||
---|---|---|---|---|
| ||||
struct timer { unsigned uint8_tchar MODE; uint32_tunsigned int DATA; unsigned uint32_tint COUNT; }; #if (sizeof(struct timer) == sizeof(unsigned char) + sizeof(unsigned int) + sizeof(unsigned int)) #error "Structure must not have any padding" #endif static_assert(offsetofsizeof(struct timer, DATA) == 4, "DATA must be at offset 4 sizeof(unsigned char) + sizeof(unsigned int) + sizeof(unsigned int), "Structure must not have any padding"); |
Static assertions allow incorrect assumptions to be diagnosed at compile time instead of resulting in a silent malfunction or runtime error. Because the assertion is performed at compile time, no runtime cost in space or time is incurred. An assertion can be used at file or block scope, and failure results in a meaningful and informative diagnostic error message.
...