Re:Oops! We Automated Bullshit
by fanf2 on Friday November 17, 2023 @09:13AM
(#38303809)
You can use sizeof() in macros but not in #if expressions.
[ Parent
| on HN ]
Re:Oops! We Automated Bullshit
by matheusmoreira on Friday November 17, 2023 @10:01AM
(#38304468)
Yeah, I meant #if directives, like static_assert. I asked it to help me statically verify my assumptions about the ELF format 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.