Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I use sizeof() in a #if? [duplicate]

I have this:

#if sizeof(int)
    #error Can't use sizeof in a #if
#endif

I get this compiler error:

missing binary operator before token "("

Why can't I use the sizeof operator here?

like image 514
Robert Avatar asked Feb 23 '10 15:02

Robert


People also ask

Why is sizeof not a function?

In C language, sizeof( ) is an operator. Though it looks like a function, it is an unary operator. For example in the following program, when we pass a++ to sizeof, the expression “a++” is not evaluated. However in case of functions, parameters are first evaluated, then passed to function.

Can you use sizeof in a macro?

The sizeof is a unary operator in C/C++ programming language, it is used to get the occupied size of a variable, constant, expression, data type, etc. It returns an unsigned integral type (size_t). Here, we will create a macro to implement own sizeof operator.

Can sizeof be used with a variable?

The size of a variable depends on its type, and C++ has a very convenient operator called sizeof that tells you the size in bytes of a variable or a type. The usage of sizeof is simple. To determine the size of an integer, you invoke sizeof with parameter int (the type) as demonstrated by Listing 3.5.

Can you do sizeof an array in C?

We can find the size of an array using the sizeof() operator as shown: // Finds size of arr[] and stores in 'size' int size = sizeof(arr)/sizeof(arr[0]);


2 Answers

Because sizeof() is calculated after the preprocessor is run, so the information is not available for #if.

C compilers are logically split into two phases, even if most modern compilers don't separate them. First, the source is preprocessed. This involves working out and substituting all the preprocessor conditionals (#if, #define, replacing defined words with their replacements). The source is then passed, processed, to the compiler itself. The preprocessor is only minimally aware of the structure of C, it has no type knowledge, so it can't handle compiler-level constructs like sizeof().

like image 162
Andrew Aylett Avatar answered Oct 15 '22 16:10

Andrew Aylett


Because you can only use literal constants in a preprocessor directive. Besides, sizeof(int) is always larger than 0, so I believe this #if would be true all the time anyway.

like image 32
Nick Avatar answered Oct 15 '22 16:10

Nick