首页 > 文章列表 > 如何在C/C++中检查变量是否为NULL?

在 C 或 C++ 中,没有特殊的方法来比较 NULL 值。我们可以使用 if 语句来检查变量是否为 null。

这里我们将看到一个程序。我们将尝试以读取模式打开系统中不存在的文件。所以该函数将返回空值。我们可以使用 if 语句来检查它。请参阅代码以更好地理解。

示例代码

#include <stdio.h>
main() {
   //try to open a file in read mode, which is not present
   FILE *fp;
   fp = fopen("hello.txt", "r");
   if(fp == NULL)
      printf("File does not exists");
   fclose(fp);
}

输出

File does not exists