~ $ cat sizeofmacro.c
#include <stdio.h>
#define pintsize(T) printf("sizeof(%s) is %zu. Big or small? You decide.\n", #T, sizeof(T))
int main(int argc, char **argv) {
pintsize(int);
pintsize(argv);
return 0;
}
~ $ gcc sizeofmacro.c && ./a.out
sizeof(int) is 4. Big or small? You decide.
sizeof(argv) is 8. Big or small? You decide.the preprocessor doesn't know anything about structs or types
>The sizeof in C is an operator, and all operators have been implemented at compiler level; therefore, you cannot implement sizeof operator in standard C as a macro or function. You can do a trick to get the size of a variable by pointer arithmetic.
> 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.