#include<iostream> using namespace std; //不带参数的宏 #define PI 3.1415926 //带参数的宏 #define FUN(x) x*x #define FUN2(x) (x)*(x) #define MAX(x,y) x>y?x:y int main(void){ int i = 10; int j = FUN(i);//j = i*i 10*10 cout << j << endl;//100 int x = 10; int y = 20; int z = MAX(x, y);//x>y?x:y cout << z << endl;//20 //特别注意: int m = FUN(2 + 3);//正确结果:2+3*2+3 错误结果:5*5 cout << m << endl;//11 //区别: int m2 = FUN2(2 + 3);//正确结果:(2+3)*(2+3) cout << m << endl;//25 system("pause"); return 0; }
什么是宏:宏是一种预处理器命令,在预编译阶段将宏名替换为后面的替换体.
宏的优点:
1.提高代码的可读性和可维护性.
2.避免函数调用,提高程序效率.