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?
The sizeof operator yields an integer equal to the size of the specified object or type in bytes. (Strictly, sizeof produces an unsigned integer value whose type, size_t , is defined in the header <stddef. h>.) A sizeof cannot be used in a #if directive, because the preprocessor does not parse type names.
You can use the sizeof operator to determine the size that a data type represents. For example: sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding.
Allows tokens used as actual arguments to be concatenated to form other tokens. defined operator. Simplifies the writing of compound expressions in certain macro directives.
Sizeof is neither a macro nor a function. Its a operator which is evaluated at compile time.
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.)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With