Does the sizeof operator work in #if preprocessor directives?

Can I use the sizeof operator in #if macros? If so, how? And if not, then why?

Does the sizeof operator work in #if preprocessor #if ?

+4
source share
4 answers

No; the sizeof() operator does not work in conditional C preprocessor directives, such as #if and #elif .

The reason is that the C preprocessor does not know anything about type sizes.

You can use sizeof() in the body of the macro #define 'd, of course, because the compiler processes the analysis of the replacement text, but the preprocessor does not. For example, a classic macro gives the number of elements in an array; these are different names, but there are:

 #define DIM(x) (sizeof(x)/sizeof(*(x))) 

This can be used with:

 static const char *list[] = { "...", ... }; size_t size_list = DIM(list); 

That you can not do:

 #if sizeof(long) > sizeof(int) // Invalid, non-working code ... #endif 

(The problem is that the condition evaluates to #if 0(0) > 0(0) under all plausible circumstances, and the parentheses make the expression invalid even with liberal preprocessor arithmetic rules.)

+6
source

The sizeof () operator cannot be used on the #if and #elif strings because the preprocessor does not parse type names.

But the expression in #define is not evaluated by the preprocessor; therefore, it is legal in the case of #define .

+6
source
 #include <stdio.h> #include <limits.h> //#if sizeof(int) == 4 #if UINT_MAX == 0xffffffffU typedef int int32; #endif //#if sizeof(long) > sizeof(int) #if ULONG_MAX > UINT_MAX typedef long int64; #elif ULLONG_MAX > ULONG_MAX typedef long long int64; #endif int main(void) { int64 i64; int32 i32; printf("%u, %u\n", (unsigned)sizeof(i64), (unsigned)sizeof(i32)); return 0; } 
+3
source

sizeof will not work in # directives. These statements were not defined during preprocessing. This is the whole point of compiling code. For sizeof to be recognized during preprocessing, you need a different compiler before the compiler.

0
source

Source: https://habr.com/ru/post/1486905/


All Articles