Look at the following code, what is the result of the output?
#include <iostream>usingnamespacestd;#define NUM 0void fun(){ #undef NUM #define NUM 100}int main(){ fun(); cout<<"NUM="<<NUM<<endl;//NUM=100; return0;}
Yes, the answer is 100, and then look at the following code:
#include <iostream>usingnamespacestd;#define NUM 0void fun();int main(){ fun(); cout<<"NUM="<<NUM<<endl;//NUM=0; return0;}void fun(){ #undef NUM #define NUM 100}
The result of the output is 0, why? At this point I came to the preliminary conclusion that the macro replacement is not to scan the entire file and then replace all, in order to solve my question, I have the macro processing after the two function code map is intercepted.
It is obvious that the replacement result is not the same.
#include <iostream> using namespace STD ; void fun (); int Main () {fun (); Out; //main.cpp:7: Error: ' Out ' is not declared in this scope //obviously made a mistake, because when the main function is not seen out. return 0 ;} void Fun () { #define out cout<< "Hello word" <<endl }//it can be concluded that macro substitution does not replace all macros at preprocessing time, //macro defined after the main function is not expanded, the macro changes or macro definitions are not visible in main.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
C + +: The misconception of macro substitution