Does the sizeof operator work in preprocessor #if directives?

。_饼干妹妹 提交于 2019-12-07 07:32:46

问题


Can we use the sizeof operator in #if macros? If yes, how? And if not, why?

Does the sizeof operator work in preprocessor #if directives?


回答1:


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

The reason is that the C pre-processor does not know a thing about the sizes of types.

You can use sizeof() in the body of a #define'd macro, of course, because the compiler handles the analysis of the replacement text and the preprocessor does not. For example, a classic macro gives the number of elements in an array; it goes by various names, but is:

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

This can be used with:

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

What you can't do is:

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

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




回答2:


A sizeof() operator cannot be used in #if and #elif line because the preprocessor does not parse type names.

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




回答3:


#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;
}



回答4:


sizeof will not work in # directives. These operators have not been defined during preprocessing. That is the whole point of compiling code. For sizeof to be recognized during preprocessing, you would need another compiler before the, well, compiler.



来源:https://stackoverflow.com/questions/17176641/does-the-sizeof-operator-work-in-preprocessor-if-directives

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!