C preprocessor #if expression

I am a bit confused about the type of expression that we can use with the #IF preprocessor in C. I tried the following code and it does not work. Explain and provide examples of expressions that can be used with the preprocessor.

#include<stdio.h> #include<conio.h> #include<stdlib.h> int c=1; #if c==1 #define check(a) (a==1)?a:5 #define TABLE_SIZE 100 #endif int main() { int a = 0, b; printf("a = %d\n", a); b = check(a); printf("a = %d %d\n", a, TABLE_SIZE); system("PAUSE"); return 0; } 
+7
source share
4 answers

A preprocessor cannot use variables from program C in expressions - it can only act on preprocessor macros. Therefore, when you try to use c in the preprocessor, you will not get what you expect.

However, you also do not get an error, because when the preprocessor tries to evaluate an identifier that is not defined as a macro, it treats the identifier as having a value of 0.

So, when you click this snippet:

 #if c==1 #define check(a) (a==1)?a:5 #define TABLE_SIZE 100 #endif 

c used by the preprocessor has nothing to do with the variable c from program C. The preprocessor looks to see if there is a macro defined for c . Since no, it evaluates the following expression:

 #if 0==1 

which of course is not true.

Since you are not using the variable c in your program, you can do the following to get the behavior according to what you are trying:

 #define C 1 #if C==1 #define check(a) (a==1)?a:5 #define TABLE_SIZE 100 #endif 

(Note that I also capitalized the macro according to the convention for macro names.)

+20
source

The preprocessor is started in the text before any compilation is completed. He does not know how to parse C. What you probably wanted instead of int c=1; , It was

 #define C 1 

and the test works the way you did it:

 #if C == 1 

The key here is that all this is defined before compilation time. The preprocessor does not care about C variables, and of course it doesnโ€™t matter what their values โ€‹โ€‹are.

Note that the convention must contain the preprocessor macro names defined in ALL_CAPS .

+2
source

The preprocessor does not evaluate C variables. It โ€œpreprocessesโ€ the source code before compiling it and, therefore, has its own language. Instead, do the following:

 #define c 1 #if c==1 #define check(a) (a==1)?a:5 #define TABLE_SIZE 100 #endif ... 
0
source

In your example, c is a symbol generated by the compiler, c does not matter until runtime, while preprocessor expressions are evaluated at build time (in fact, as the name implies, before the compiler processes the code) so they can only work on pre-processor characters that exist at build time.

In addition, such expressions must be compilation time constants or, more precisely, the exact preprocessing time constant, since compiler constant expressions such as sizeof(...) , for example, are also not defined during preprocessing.

0
source

All Articles