Skip to content

Commit da37e9e

Browse files
committed
Avoid evaluating the sizeof in C preprocessor
The C preprocessor operates purely on text, substituting macros and evaluating simple arithmetic expressions involving literal constants. It does not understand types, so it cannot evaluate operators like sizeof that require type information and compile-time type checking. Change-Id: Id8b453db78571d67a8b7f95b240b71df212d7796
1 parent 3adba58 commit da37e9e

File tree

1 file changed

+3
-5
lines changed

1 file changed

+3
-5
lines changed

CONTRIBUTING.md

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -766,15 +766,13 @@ typedef struct {
766766
uint16_t periodic : 1; /* offset 6 bit 0 */
767767
} mytimer_t;
768768
769-
/* Preprocessor check of timer register layout byte count. */
770-
#if (sizeof(mytimer_t) != 8)
771-
#error mytimer_t struct size incorrect (expected 8 bytes)
772-
#endif
769+
_Static_assert(sizeof(mytimer_t) == 8,
770+
"mytimer_t struct size incorrect (expected 8 bytes)");
773771
```
774772
775773
To enhance portability, use standard-defined types (e.g., `uint16_t`, `uint32_t`) and avoid relying on compiler-specific behavior.
776774
Where precise control over memory layout is required, such as in embedded systems or when interfacing with hardware,
777-
always verify the structure size and layout using static assertions or preprocessor checks.
775+
always verify the structure size and layout using static assertions.
778776
779777
#### Avoid extreme portability
780778

0 commit comments

Comments
 (0)