
Question:
I have below code.
Where I would like to undefine the PORT
after 5
iterations. But when i am running this program the output comes like
PORT
MOB
PORT
MOB...10 times
So, if I would to change it at run time how can I do this.
I have declared PORT
inVS project->Propoties->C/C++->Preprocessor
int main()
{
int i;
for(i = 0; i <= 10; i++)
{
#ifdef PORT
printf("PORT\n");
#endif
if(i == 5)
{
#ifdef PORT
#undef PORT
#endif
#define MOB 1
}
#if MOB
printf("MOB\n");
#endif
}
return 0;
}
Answer1:The pre-processor (as implied by the name) does what it does as the <em>first</em> step in compilation (or, depending on your viewpoint, before compilation completely). Things that happen at run-time can't control things that happened previously. You can't change anything done by the pre-processor at run time.
To get the desired effect, you could change from trying to use a pre-processor definition to using a normal variable, or normal flow control.
for (int i=0; i<5; i++)
printf("PORT\n");
for (int i=0; i<5; i++)
printf("MOB\n");
...or:
for (int i=0; i<10; i++)
printf(i < 5 ? "PORT\n", "MOB\n");
Although you didn't mention them, I'll add that C++ templates have much the same limitation, so trying to do this with them is <em>likely</em> (though perhaps a little less certain) to turn out essentially similar. Templates do give you <em>more</em> ability to inspect and modify their results in accordance with the rest of the program, but only a little. Ultimately, template parameters need to be compile-time constants so the templates can be resolved at compile time.
Answer2:This is impossible. Preprocessor directives are part of compilation. There's no such thing as a runtime preprocessor, you can't change directives in runtime. A binary file does not know about preprocessor directives.
Answer3:This can't be done.
The preprocessor runs as one of the first passes on your source file before it is compiled.
You can not manipulate the preprocessor at runtime of your program. Use normal variables instead.
Answer4:You can't. The preprocessor is run as a separate step <em>before</em> the compilation. There is no way to do it runtime.
You have to do it using normal if
and else
handling with variables.