在最近写代码时会遇到判断是否为空指针,看别人的代码有时候用NULL有时候用nullptr,所以查了一下他们之间的区别:
首先NULL和nullptr都能代表空指针,但是在C++中代表的含义是不同的,NULL被定义为整型变量0或者直接就是由0转化成的void*。它的定义代码如下:
#ifndef NULL
#ifdef __cplusplus
#define NULL 0
#else
#define NULL ((void *)0)
#endif
#endif
可以看出在C++中优先将NULL定义为int型的0,而nullptr直接默认为void*。下面我们通过代码来看一下:
#include <iostream>
using namespace std;
void func(void* t)
{
cout << "func1" << endl;
}
void func(int i)
{
cout << "func2" << endl;
}
int main()
{
func(NULL);
func(nullptr);
system("pause");
return 0;
}
上面程序运行结果为:
可以看出NULL直接默认传入的是整型变量,所以在C++中使用nullptr相对是比较保险的。