- C language
- preprocessor
- here
Preprocessor conditional branching
The preprocessor has a conditional branching syntax.
#ifdef-if a macro is defined
If a macro is defined, it can be expressed by "#ifdef".
#ifdef macro name // process #endif
This is a sample of "#ifdef".
#include <stdio.h> #define MYAPP_FOO int main (void) { #ifdef MYAPP_FOO printf("Hello\n"); #endif }
If macro called "MYAPP_FOO" is defined in #define, "Hello" is output, and if this line is removed, nothing is output. Hmm.
#ifndef --If the macro is not defined
If a macro is not defined, can be represented by "#ifndef".
#ifndef macro name // process #endif
"#Ifndef" is often used when writing include guard.
This is a sample of "#ifndef".
#include <stdio.h> int main (void) { #ifndef MYAPP_FOO printf("Hello\n"); #endif }
If the macro called "MYAPP_FOO" is not defined in #define, "Hello" is output, and if it is defined, nothing is output. It will not be.
#if --If the conditions are met
You can describe the processing when the condition is met with "#if". You can use the comparison operator, negation operator, and defined. Comparison operations can be performed using only integer constants. If the comparison operation did not define a macro, the value is assumed to be 0.
#if condition // process #endif
This is a sample of "#if".
#include <stdio.h> #define MYAPP_FOO 5 int main (void) { #if defined(MYAPP_FOO) printf("MYAPP_FOO is defined\n"); #endif #if! defined(MYAPP_FOO) printf("MYAPP_FOO is not defined\n"); #endif #if defined(MYAPP_FOO) #if MYAPP_FOO> 3 printf("MYAPP_FOO is defined and greater than 3\n"); # endif #endif }
#elif, #else
Multiple conditions are applied with "#elif", and processing is applied when the conditions are not satisfied with "#else".
#include <stdio.h> #define MYAPP_FOO 5 int main (void) { #if MYAPP_FOO> 10 printf("MYAPP_FOO is greater than 10\n"); #elif MYAPP_FOO> 3 printf("MYAPP_FOO is greater than 3\n"); #else printf("MYAPP_FOO is others\n"); #endif }
Is it possible to use the sizeof operator with the comparison operator?
Yes, you cannot use the sizeof operator with the preprocessor comparison operator.
This means that in principle it is not possible to make 32-bit or 64-bit decisions using the preprocessor.
It must be given as a macro definition from outside C.
Also, if a macro definition for judgment has already been given, it can be used. For example, gcc is used to judge 32bit.
#include <stdio.h> int main () { #ifdef __code_model_32__ #else #endif }