Hi,
Please help me to understand what really happens in the below code.
#define num 20
main()
{
printf("%d,",num);
func();
printf("%d",num);
}
void func()
{
#undef num
#define num 50
}
The output is 20,20.
I expect the output to be 20,50
It seems to be strange to understand. Help me
Thanks in advance,
Chella
Ok,let's see:
If I run your program I get 20,20( Dev-C++ on WinXp),but if you comment the function and add
- #undef num
-
#define num 50
directly into main I got 20,50 which is correct.
Now,zoddila got 50,50 on Linux which makes me think that result is platform depended.But when I tried the following:
- void func()
-
{
-
#define num2 50
-
}
and tried calling it in main it said that num2 is undefined,so it must reside on stack which is cleared when function finishes.So,furthermore I tried:
- void func()
-
{
-
#undef num
-
#define num 50
-
printf("%d\n",num);
-
}
and result was correct.As the conclusion:
Never define a macro inside a function.
You can define it in main and it will seem as normal but it isn't.Macro will have other value in other functions,so always declare them in global namespace..
Savage