#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 语言里并无不同,但推荐使用前者。
- "NULL" 的本质是个宏,并非是 build-in 常量,C99 中甚至可以自行定义,故尽量避免使用它去判断。[1]
- 当
!s
与s == NULL
表示同一含义的时候,使用前者。(程序员的原则:Brevity Can Be a Virtue) - 前者更为业界所认可,用来判断有保障。[2]
- [1] NULL 宏定义在7.17 Common definitions <stddef.h>
以及 Question 5.5- [2] 见 Question 5.3
多一嘴,在 C++ 里,
NULL
仅存在于 C++0x 标准中,在 C++11 中,要求使用nullptr
来表示。
webkit coding style要求用前者。。。
http://www.webkit.org/coding/coding-style.html#zero-comparison