码迷,mamicode.com
首页 > 编程语言 > 详细

C++:宏替换的误区

时间:2015-08-28 17:50:14      阅读:194      评论:0      收藏:0      [点我收藏+]

标签:宏替换   defcon   

看下面的代码,输出的结果是什么呢?

#include <iostream>
using namespace std;
#define NUM 0

void fun()
{
    #undef NUM
    #define NUM 100
}
int main()
{
    fun();
    cout<<"NUM="<<NUM<<endl;//NUM=100;
    return 0;
}

没错,答案是100,再看下面这段代码:

#include <iostream>
using namespace std;
#define NUM 0
void fun();

int main()
{
    fun();
    cout<<"NUM="<<NUM<<endl;//NUM=0;
    return 0;
}

void fun()
{
    #undef NUM
    #define NUM 100
}

输出的结果是0,为什么呢?此刻我得出的初步结论是,宏替换并不是扫描全文件然后全部替换,为了解决我的疑问,我把宏处理之后两个函数代码图截取下来了。
技术分享
技术分享
很明显替换结果并不一样。

#include <iostream>
using namespace std;
void fun();
int main()
{
    fun();
    OUT;
    //main.cpp:7: error: ‘OUT’ was not declared in this scope
        //明显出错了,因为到main函数的时候看不到OUT。
    return 0;
}
void fun()
{
#define OUT cout<<"hello word"<<endl
}
//由此可以得出,宏替换并不是在预处理的时候替换所有的宏,
//只会替换在main函数之前可见的,如果定义在main函数后面的
//宏定义是不会展开的,所以在main里面是看不到宏改变或者宏定义的。

版权声明:本文为博主原创文章,未经博主允许不得转载。

C++:宏替换的误区

标签:宏替换   defcon   

原文地址:http://blog.csdn.net/liuhuiyan_2014/article/details/48053037

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!