简体   繁体   中英

Preprocessor #if directive

I am writing a big code and I don't want it all to be in my main.c so I wrote a .inc file that has IF-ELSE statement with function and I was wondering can it be written like this:

#if var==1
process(int a)
{
    printf("Result is: %d",2*a);
}
#else
process(int a)
{
    printf("Result is: %d",10*a);
}
#endif

I tried to compile it but it gives me errors or in best case it just goes on the first function process without checking the var variable (it is set to 0).

The preprocessor doesn't "know" the value of any variable, because it does its work even before compilation, not at runtime.

In the condition of a preprocessor #if you can only evaluate #define 'd symbols and constant expressions.

The particular example you are showing can be simply converted to:

printf("Result is: %d", (var == 1 ? 2: 10) * a);

This is what you want:

process(int a)
{
   if (var == 1)
      printf("Result is: %d",2*a);
   else
      printf("Result is: %d",10*a);
}

It is important to remember that the preprocessor is its own program and not a part of the program you are writing. The variable "var" (or whatever var represents here) is not in the the namespace of the preprocessor's identifiers.

Just to complete. For a standard conforming compiler your code would always be correct. In #if expression evaluations all identifiers that are not known to the preprocessor are simply replaced with 0 (or false if you want). So in your particular case, if var is just a variable and not a macro, the result would always be the second version of your function.

For the error that you report for MS: I did know that the MS compilers aren't standard conforming, but I wasn't aware that they don't even fulfill such basic language requirements.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM