#include <stdio.h>
int main(int argc, char const *argv[]) {
char *s = "hello";
if (!s) {
fprintf(stderr, "s is null\n");
} else {
fprintf(stderr, "%s\n", s);
}
if (s == NULL) {
fprintf(stderr, "s is null\n");
} else {
fprintf(stderr, "%s\n", s);
}
return 0;
}
这两种方法貌似都能判断字符指针是否为空,有什么不一样的吗?用哪种比较好?
在 C 语言里并无不同,但推荐使用前者。
!s
与s == NULL
表示同一含义的时候,使用前者。(程序员的原则:Brevity Can Be a Virtue)<stddef.h>
中,通常有两种定义方式:或
另见: 7.17 Common definitions <stddef.h>
以及 Question 5.5
多一嘴,在 C++ 里,
NULL
仅存在于 C++0x 标准中,在 C++11 中,要求使用nullptr
来表示。