Trying_Harder said:
p.s: Can someone please attend to my question above?
Here's the original code:
[Trying_Harder]
| sample.h
| #define BLAH 10
|
| sample.c
| /* This should print 10 */
| printf("\n %d ", BLAH);
|
| func1();
|
| printf("\n %d ", BLAH);
|
| func1()
| {
| #undef BLAH
| #define BLAH 15
| /* This should print 15, but BLAH has a local scope */
| printf("\n %d ", BLAH);
|
| }
Here's the (correct) answer you don't find convincing:
[Eric Sosman]
|> The numbers output would be 10, 15, and 10, in that order.
|> BLAH does not have "a local scope" in func1(); BLAH remains
|> defined as 15 all the way to the end of the compilation.
Here's the question I think you're referring to:
[Trying_Harder]
| If don't find this answer not convincing. If this was true then why
| is the 3rd `printf' (in main) printing out 10 ? According to this
| explanation it should print out 15 everywhere (after this "redefinition")
| regardless of the scope.
Preprocessor replacement works on the text of the source file, so
occurrences of "BLAH" in the lines following the "#undef", "#define"
directives are replaced with "15" during an early stage of
compilation. Occurrences of "BLAH" before this (but following the
first "#define") are replaced with "10". After all this has taken place
the output from "sample.c" looks something like this:
printf("\n %d ", 10);
func1();
printf("\n %d ", 10);
func1()
{
printf("\n %d ", 15);
}
Note that this all takes place at "compile-time", i.e. before the
program is run at all. Further stages of compilation translate your
program into some sort of executable format, by which point there is
no trace of "#define" or "BLAH" left; the preprocessor directives have
already been executed and only "runnable" code remains.
"BLAH" is not like a variable, which is initialised at runtime.
"func1()" does not change the value of "BLAH". The fact that the
second "#define" is textually inside the body of "func1()" is
irrelevant; there is nothing left of "BLAH" or its various definitions
by the time "func()" is called.
Jeremy.