从缺陷中学习C++(02)

本文深入探讨了宏定义在C++编程中的常见问题,包括计算表达式的错误与正确方式、宏名与系统库冲突的解决方案,以及多语句宏定义的正确使用方法。通过实例分析,帮助读者理解并避免宏定义的常见陷阱。

2.宏定义问题

利用宏定义计算(2*x + 2*y)*z

//错误代码

#define PERIMETER(X,Y)   2*X + 2*Y
void main() {

	int x = 5, y = 2, z = 8;
	int result = PERIMETER(x, y) * z;
	cout << result << endl;
}

由于宏替换本身只是文本替换,上述代码变成result = 2*x +2*y*z;

//正确代码

#define PERIMETER(X,Y)   (2*(X) + 2*(Y))
void main() {

	int x = 5, y = 2, z = 8;
	int result = PERIMETER(x, y) * z;
	cout << result << endl;
}

宏定义命名与系统库同名问题

//文件a.cpp中

#define map  _cxx::hash_map
map<long, long> myhashmap

//文件b.cpp中

#include <map>
#include "a.cpp"
map<long, long> mymap;

宏编译在预编译阶段执行,所以在b.cpp中,代码行map<long,long>mymap在预编译时被替换成_cxx::hash_map<long, long> mymap,不会使用b.cpp中包含的#include<map>,只需修改a.cpp为smap即可。

//正确代码,修改a.cpp中的宏名字smap

#define smap  _cxx::hash_map
map<long, long> myhashmap

多语句宏定义使用错误

//错误代码

#define EXIT(info) std::cerr<<info<<std::endl;exit(1)

void main() {

	int data = 0;
	if (data < 0) 
		EXIT("data is a negative number!");
		std::cout << "data is a non-negative number." << std::endl;
}

当data为负数时,打印"data is a negative number!",然后程序退出;当data大于等于0时,程序不会打印。只需用大括号将宏定义括起来。

#define EXIT(info) (std::cerr<<info<<std::endl;exit(1);)

void main() {

	int data = 0;
	if (data < 0) 
		EXIT("data is a negative number!");
		std::cout << "data is a non-negative number." << std::endl;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值