Reputation: 831
I am a bit confused on the type of expression we can use with the #IF preprocessor in the C language. I tried the following code, and it isn't working. Please explain and provide examples for 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;
}
Upvotes: 17
Views: 42904
Reputation: 8150
The preprocessor does not evaluate C variables. It "preprocesses" the source code before it is compiled and thus has its own language. Instead do this:
#define c 1
#if c==1
#define check(a) (a==1)?a:5
#define TABLE_SIZE 100
#endif
...
Upvotes: 0
Reputation: 93476
In your example c
is a compiler generated symbol, c
has no value until run-time, whereas preprocessor expressions are evaluated at build-time (in fact as the name suggests before the compiler processes the code), so can only operate on pre-processor symbols which do exist at build time.
Moreover such expressions must be compile time constants, or in fact more exactly preprocessing time constant, since compiler constant expressions such as sizeof(...)
for example are also not defined during pre-processing.
Upvotes: 0
Reputation: 50941
The preprocessor is run on the text, before any compilation is done. It doesn't know how to parse C. What you probably wanted instead of int c=1;
was
#define C 1
and the test works the way you had it:
#if C == 1
The key here is that this is all defined before compile time. The preprocessor doesn't care about C variables, and certainly doesn't care what their values are.
Note that the convention is to have preprocessor macro names defined in ALL_CAPS
.
Upvotes: 5
Reputation: 340198
The preprocessor cannot use variables from the C program in expressions - it can only act on preprocessor macros. So when you try to use c
in the preprocessor you don't get what you might expect.
However, you also don't get an error because when the preprocessor tries to evaluate an identifier that isn't defined as a macro, it treats the identifier as having a value of zero.
So when you hit this snippet:
#if c==1
#define check(a) (a==1)?a:5
#define TABLE_SIZE 100
#endif
The c
used by the preprocessor has nothing to do with the variable c
from the C program. The preprocessor looks to see if there's a macro defined for c
. Since there isn't, it evaluates the following expression:
#if 0==1
which is false of course.
Since you don't appear to use the variable c
in your program, you can do the following to get behavior in line with what you're trying:
#define C 1
#if C==1
#define check(a) (a==1)?a:5
#define TABLE_SIZE 100
#endif
(Note that I also made the macro name uppercase in keeping with convention for macro names.)
Upvotes: 30