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/