1.定义常量
#define ARRMAX 50 int arr[ARRMAX];
(这种做法不如直接用const来直接定义常量。)
2.代替模板函数或者内联函数,将函数定义成宏。执行效率很快
#define SWAP(a,b) do\ {\ decltype(a) temp = a;\ a = b;\ b = temp;\ }while(0)
[1]函数定义块如果需要换行,那么换行是结尾需加反斜杠
[2]可以利用decltype来获得函数参数的类型,方便函数中内容的执行
[3]利用do while(0)可以使函数中的变量变成局部变量,且使语法清晰减少出错
[4]有时可用这种宏的方式可以代替c++的模板,执行效率要比模板快
[5]因为是文本替换,所以尽量不要把分号写进去,在调用的时候补充分号
3.预编译逻辑判断
#include <iostream> #include <string> #include "test.h" using namespace std; #define DEBUG void MyLog(string logger) { #if defined(DEBUG) cout << "Logger In This:" << logger << endl; #endif } int main(int argc, char** argv) { #if defined(WIN32) cout<<"this device is WIN32" << endl; #endif #if !defined(WIN32) cout<<"this device is not WIN32" << endl; #endif #if defined(WIN32)&&defined(LINUX) cout <<"win32 and linux" << endl; #endif MyLog("1"); MyLog("2"); MyLog("3"); #undef DEBUG MyLog("4"); system("pause"); }
可以利用#if #elif #else #endif来进行编译时的逻辑处理。逻辑判断的内容主要是是否define了某个宏。检查是按照文件声明顺序依次来的。
[1]可以使用与或非逻辑判断
[2]一旦代码开始编译函数后,#define 和 #undef将被无效化,要在文件开头处使用#define 或 #undef
#include <iostream> #define DEBUG //有效 using namespace std; #define DEBUG //有效 int i = 10; #define DEBUG //有效 int add(int i , int j) { #define DEBUG //无效 } #define DEBUG //无效 int main() { #define DEBUG //无效 }
[3]可利用这个防止头文件被重复加载,也能用这个来编写Logger,只需修改某个头文件的DEBUG宏,就能让程序中的所有Logger开启或关闭打印。