如何在 C/C++ 中檢查變數是否為 NULL?”


在 C 或 C++ 中,沒有特殊方法來比較 NULL 值。我們可以使用 if 語句來檢查變數是否為 null。

這裡我們會看到一個程式。我們將嘗試以讀取模式開啟一個不在系統中的檔案。因此,該函式將返回 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

更新於:2019 年 7 月 30 日

24K+ 瀏覽量

開啟你的職業生涯

完成課程獲取認證

立即開始
廣告
© . All rights reserved.