Reputation: 31
I've tried to check around, but I can't seem to find an answer.
I'm writing some C code, and I want to figure out if given int i
, is that defined as a macro somewhere. For instance, running a for
loop checking if the counter is a macro. I've come up with the following, but it give me warnings when I compile, so I'm assuming its bad code
for(int i = 1; i < 25; i++){
#define DEFINED 1
#ifndef i
#define DEFINED 0
#endif
int a = DEFINED;
if(a){
bla bla
}
}
Thank you so much.
Upvotes: 0
Views: 303
Reputation: 21562
The preprocessor doesn't "know" C. Barring special directives like #error
and #pragma
, it is much just a text-substitution system.
#if((n)def)
only works for macros declared with the preprocessor with the #define
keyword; C variables like int i
are not macros.
To give you a better idea:
#include <stdio.h>
#define MYFORLOOP for(i = 0; i < 25; i++)
int main()
{
int i;
int data[25];
MYFORLOOP
{
data[i] = i;
}
MYFORLOOP
{
printf("%d\n", data[i]);
}
return 0;
}
The code is then preprocessed before it is actually compiled, so what the compiler actually "sees" is:
// < The contents of stdio.h, including any headers it includes itself >
int main()
{
int i;
int data[25];
for(i = 0; i < 25; i++)
{
data[i] = i;
}
for(i = 0; i < 25; i++)
{
printf("%d\n", data[i]);
}
return 0;
}
The reason #ifdef i
would fail is because the variable i
is not a #define
macro.
Upvotes: 0
Reputation: 224387
The reason you're getting a warning is because you redefine DEFINED
in the event the macro i
is not defined. You need to define this macro entirely within an #if
.
#ifndef i
#define DEFINED 0
#else
#define DEFINED 1
#endif
Upvotes: 0
Reputation: 170163
Short answer: You can't use the value of i
as a condition in a preprocessor expression. You can't even check if it's defined.
Longer answer: preprocessing is one of the early translation stages. It happens even before the code is compiled. The value of i
is available only during run time. Meaning after the program has been compiled, linked, and then executed. The two stages are as far apart as they can be.
You can't check if an i
variable is defined either, since the symbol i
is known as a variable only during the compilation stage (again, after the preprocessor has finished its run).
It's true that the preprocessor allows you to conditionally compile code, but you cannot base those conditions on things which are known only at later translation stages.
Upvotes: 3