Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the sizeof operator work in preprocessor #if directives?

Tags:

c

sizeof

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?

like image 267
Varun Chhangani Avatar asked Jun 18 '13 18:06

Varun Chhangani


People also ask

Can sizeof be used in macro?

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.

What is sizeof operator used for?

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.

What are preprocessor operators?

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.

Is sizeof () a macro or a function?

Sizeof is neither a macro nor a function. Its a operator which is evaluated at compile time.


Video Answer


2 Answers

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.)

like image 152
Jonathan Leffler Avatar answered Nov 09 '22 15:11

Jonathan Leffler


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.

like image 45
S J Avatar answered Nov 09 '22 16:11

S J