#if sizeof(int) != 4
/* do something */
Using sizeof inside #if
doesn't work while inside #define
it works, why?
#define size(x) sizeof(x)/sizeof(x[0]) /*works*/
#if sizeof(int) != 4
/* do something */
Using sizeof inside #if
doesn't work while inside #define
it works, why?
#define size(x) sizeof(x)/sizeof(x[0]) /*works*/
The reason it doesn't work is because the pre-processor macros are 'evaluated' in a pass before the code reaches the compiler. So in the if pre-processor directive, the sizeof(int) (actually the sizeof(int) != 4) cannot be evaluated because that is done by the compiler, not the pre-processor.
The define statement though, simply does a text substitution, and so when it comes to the compiler, everywhere you had 'size(x)' you would have 'sizeof(x)/sizeof(x[0])' instead, and then this evaluates there at the compile stage... at every point in the code where you had 'size(x)'
If you want to check the size of the integer in the processor, use your make system to discover the size of integer on your system before running the preprocessor and write it to a header file as e.g.
#define SIZEOF_INT 4
, include this header file and do#if SIZEOF_INT == 4
For example, if you use cmake, you can use the
CMAKE_SIZEOF_INT
variable which has the size of the integer which you can put in a macro.The compiler doesn't touch either line. Rather, the preprocessor rips through the file, replacing any instances of size(x) with your macro. The compiler DOES see these replacements.