c++ - '\0' 和 NULL 可以互换使用吗?

标签 c++ null

NULL 常用于指针的上下文中,通过多个标准库(如 <iostream>)中的宏定义为整数 0 . '\0'是空字符,是 8 位零。顺便说一句,8 位零相当于整数 0 .

在某些情况下,虽然它被认为是可怕的风格,但这两者可以互换:

int *p='\0';
if (p==NULL) //evaluates to true
    cout << "equal\n";

或者

char a=NULL;
char b='\0';
if (a==b) //evaluates to true
    cout << "equal again\n";

仅关于 SO 就已经有很多类似的问题了;例如,这个问题的最佳答案 (What is the difference between NULL, '\0' and 0) 说“它们并不是一回事”。

谁能提供一个例子NULL\0不能互换(最好是实际应用而不是病态)?

最佳答案

Could anyone provide an example that NULL and \0 cannot be interchanged?

NULL'\0' 之间的差异可能会影响重载解析。

示例(check it on Coliru):

#include <iostream>

// The overloaded function under question can be a constructor or 
// an overloaded operator, which would make this example less silly
void foo(char)   { std::cout << "foo(char)"  << std::endl; }
void foo(int)    { std::cout << "foo(int)"   << std::endl; }
void foo(long)   { std::cout << "foo(long)"  << std::endl; }
void foo(void*)  { std::cout << "foo(void*)" << std::endl; }

int main()
{
    foo('\0'); // this will definitely call foo(char)
    foo(NULL); // this, most probably, will not call foo(char)
}

请注意,Coliru 使用的 gcc 编译器将 NULL 定义为 0L,对于本示例,这意味着 foo(NULL) 解析为 foo(long) 而不是 foo(void*)This answer详细讨论了这方面。

关于c++ - '\0' 和 NULL 可以互换使用吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40395066/

相关文章:

c++ - boost::bind、boost::lambda::bind 和 boost::phoenix::bind 之间的区别

python - 仅使用一张深度图像的 OpenCV 视差图后过滤

c++ - 使用 void* 而不是 bool 是一种可取的做法吗?

c++ - 如何用直引号C++替换特殊引号

coldfusion - 如何检查 ColdFusion 查询循环中的返回值是否为空值

c++ - 动态创建的字符串分配在堆或堆栈上 - C

vb.net - 保护变量免受空值影响

null - 正确使用 NotNull

mysql - SQL查询,仅当列不为空时才选择,否则不选择

java - 对字符串和 null 关键字的 Concat 操作