2 ms·
You can use sizeof() in macros but not in #if expressions.
by fanf2 3y ago
You can use sizeof() in macros but not in #if expressions.
- matheusmoreira 3y agoYeah, I meant #if directives, like static_assert. I asked it to help me statically verify my assumptions about ELF files and it gave me some pretty insane code. Here's the excerpt: > Certainly, you can use a combination of sizeof and #error directives for conditional compilation to achieve a similar effect without static_assert. // Compile-time check for structure sizes #if sizeof(Elf32_Phdr) != sizeof(((Elf32_Ehdr*)0)->e_phentsize) #error "32-bit structure size mismatch" #endif #if sizeof(Elf64_Phdr) != sizeof(((Elf64_Ehdr*)0)->e_phentsize) #error "64-bit structure size mismatch" #endif > In this example, if the structure sizes don't match, the preprocessor will generate an error at compile time using the #error directive. > I didn't know sizeof could be used with the C preprocessor > Yes, sizeof can be used in certain contexts within the C preprocessor. > It's commonly employed in combination with the #if and #error directives to perform compile-time checks on sizes or other constants. > This usage allows you to catch potential issues during compilation rather than at runtime. I should probably go sleep a bit before I embarrass myself any further. After nearly 24 hours awake it seems I have lost the ability to tell macros and directives apart.
- fanf2 3y agostatic_assert() is not a preprocessor thing, so you can use sizeof() there without trouble. It does have other limitations: it’s syntactically a declaration which makes it painful to use in macros without wrapping it in the GNU C statement-expression extension.