C++ define用法

转载地址:https://www.cnblogs.com/AkazaAkari/p/6899935.html

 

1 定义常量

#define ARRMAX 50

int arr[ARRMAX];

 

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开启或关闭打印。

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值