【ThinkingInC++】47、关于宏的使用,探讨使用宏的缺点

来源:互联网 发布:淘宝助理上传宝贝慢 编辑:程序博客网 时间:2024/06/08 03:08
/*** 书本:【ThinkingInC++】* 功能:关于宏的使用,探讨使用宏的缺点* 时间:2014年9月11日07:50:54* 作者:cutter_point*/#include"../require.h"#include<fstream>using namespace std;//这里就是用BAND(x)代替后面的那一串函数#define BAND(x) (((x)>5 && (x)<10) ? (x) : 0)int main(){    ofstream out("macro.txt");    assure(out, "macro.txt");    for(int i=4 ; i < 11 ; ++i)    {        int a=i;        out<<"a= "<<a<<endl<<'\t';        //这里就要小心了,记住用宏代替之后的结果展开应该是这样的        //(((++a)>5 && (++a)<10) ? (++a) : 0)这里调用了三次++a,        //好的,代码一旦执行,问题马上就体现出来了        out<<"BAND(++a)="<<BAND(++a)<<endl;        out<<"\t a="<<a<<endl;    }    return 0;}/*执行结果:a= 4BAND(++a)=0 a=5a= 5BAND(++a)=8 a=8a= 6BAND(++a)=9 a=9a= 7BAND(++a)=10 a=10a= 8BAND(++a)=0 a=10a= 9BAND(++a)=0 a=11a= 10BAND(++a)=0 a=12*/

0 0