首页  >  文章  >  后端开发  >  如何在C/C++中检查变量是否为NULL?

如何在C/C++中检查变量是否为NULL?

王林
王林转载
2023-09-05 16:25:09870浏览

如何在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

以上是如何在C/C++中检查变量是否为NULL?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除