C + +: The misconception of macro substitution

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.