當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C語言 宏 NULL()用法及代碼示例


描述

C 庫宏NULL是空指針常量的值。它可以定義為((void*)0), 0 或者0L取決於編譯器供應商。

聲明

以下可能是 NULL 宏的聲明,具體取決於編譯器。

#define NULL ((char *)0)

or

#define NULL 0L

or

#define NULL 0

參數

  • NA

返回值

  • NA

示例

下麵的例子展示了 NULL 宏的用法。

#include <stddef.h>
#include <stdio.h>

int main () {
   FILE *fp;

   fp = fopen("file.txt", "r");
   if( fp != NULL ) {
      printf("Opend file file.txt successfully\n");
      fclose(fp);
   }

   fp = fopen("nofile.txt", "r");
   if( fp == NULL ) {
      printf("Could not open file nofile.txt\n");
   }
   
   return(0);
}

假設我們有一個現有文件file.txtnofile.txt不存在。讓我們編譯並運行上麵的程序,它會產生以下結果——

Opend file file.txt successfully
Could not open file nofile.txt

相關用法


注:本文由純淨天空篩選整理自 C library macro - NULL()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。