用 NULL 或者符号 ! 判断 C 语言字符指针有什么区别?

#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;
}

这两种方法貌似都能判断字符指针是否为空,有什么不一样的吗?用哪种比较好?

阅读 7.5k
3 个回答

在 C 语言里并无不同,但推荐使用前者。

  1. "NULL" 的本质是个宏,并非是 build-in 常量,C99 中甚至可以自行定义,故尽量避免使用它去判断。[1]
  2. !ss == NULL 表示同一含义的时候,使用前者。(程序员的原则:Brevity Can Be a Virtue)
  3. 前者更为业界所认可,用来判断有保障。[2]

  • [1] NULL 宏定义在<stddef.h>中,通常有两种定义方式:
c#define NULL ( (void *) 0)

c#define NULL 0

C11(ISO/IEC 9899:201x) §6.3.2.3 Pointers Section 3

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant

另见: 7.17 Common definitions <stddef.h>
以及 Question 5.5


多一嘴,在 C++ 里,NULL 仅存在于 C++0x 标准中,在 C++11 中,要求使用 nullptr 来表示。

完全一样,看个人习惯.从可读性来说,推荐后者

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进