程式語言復習札記:null 判斷
2007 年 六月 24 日 (星期日) 8:51 am分類:電腦
標籤: programming, plnotes
程式語言學得多了、用得久了,細節難免遺忘,甚至張冠李戴。有些事情可以一知半解、能用且用,但某些很基本的議題,像 scope、lifetime、參數傳遞,如果缺乏正確認知,很容易就會埋下不定時炸彈。
我已經厭倦一再翻書或上網考察這些事情了。我決定要趁此機會,替我常用、或者即將要用的程式語言,進行通盤考察,一次解決這些對我而言算是 FAQ 等級的問題。
首先是 null 的判斷。我所考慮的程式語言計有 C/C++、C#、Java、JavaScript、Perl、PHP、Ruby。
C/C++
C 語言裡,指標 null 與否,可由 0 這個整數 literal(正式名稱叫做 “null pointer constant”;見 C99 §6.3.2.3),或是較具可讀性的 NULL 巨集符號來判斷:
#include <stddef.h> /* NULL */
#include <stdbool.h> /* C99: true, false */
bool is_null(void* p)
{
if (p == NULL) /* if (!p) */
return true;
return false;
}
至於 C++ 的指標,The C++ Programming Language §5.1.1 如是說:
由於 C++ 有更嚴格的型別檢查系統,因此在 C++ 裡,直接使用
0而不要用任何NULL巨集,比較不會出問題。如果你覺得還是需要定義一個NULL的話,請用:
const int NULL = 0;
C++ 的 reference 規定一定要有個被指涉的對象(見 C++ §8.3.2),因此沒有所謂的 “null reference”。
C#
C# 的 object reference 是否為 null,可由 null 這個語言保留字來判斷:
public static bool is_null(object obj)
{
if (obj == null)
return true;
return false;
}
Java
Java 的 object reference 是否為 null,可由 null 這個語言保留字來判斷:
public static boolean is_null(Object obj)
{
if (obj == null)
return true;
return false;
}
JavaScript
JavaScript 是一種動態型別語言,所以要再細分兩種情況:
- 變數名稱若不存在,
typeof(name)會是'undefined'。 - 變數名稱若存在,但未賦予實值,則會是
null。
整個邏輯可歸納如下:
function is_null(obj)
{
if (typeof(obj) == 'undefined' || obj == null)
return true;
return false;
}
參考資料:What’s the most reliable way to check a javascript null?
Perl
Perl 是一種動態型別語言,以高自由度聞名,高到即使你沒有事先宣告變數,或者雖然宣告過但尚未賦予初值,你的程式依然可以直接把它當成 rvalue 來使用。根據 Learning Perl, 3/e §2.11 所述:
What happens if you use a scalar variable before you give it a value? Nothing serious, and definitely nothing fatal.
Variables have the special
undefvalue before they are first assigned, which is just Perl’s way of saying “nothing here to look at — move along, move along.” If you try to use this “nothing” as a “numeric something,” it acts like0. If you try to use it as a “string something,” it acts like the empty string.
所以對於 Perl,不管是第一種情況:變數名稱不存在,還是第二種情況:變數名稱雖然存在、但尚未賦予實值,標準函數 defined(name) 一律傳回 false 值。
不過,高自由度往往意謂著容易出錯。所以在寫 Perl 程式時,最好還是啟用最嚴格的檢驗標準:
#!/usr/bin/perl -w use strict;
PHP
PHP 是一種動態型別語言,所以要再細分兩種情況:
整個邏輯可歸納如下:
function is_null_myversion($obj)
{
if (!isset($obj) || is_null($obj))
return true;
return false;
}
如果要處理的對象是 named constant,就得改用 defined(name) 來檢測。
Ruby
Ruby 是一種動態型別語言,也是一個徹徹底底的物件導向語言,everything is object。它的 object reference 是否為 null,可由 name.nil? 這個 method 來判斷。
def is_null(obj)
if (obj.nil?)
return true
else
return false
end
end


追蹤留言回應:以
引用通告 (trackback):![[add to funP]](http://william.cswiz.org/blog/wp-content/themes/william/images/add-funp.png)
![[add to HEMiDEMi]](http://www.hemidemi.com/sticker/user/roxytom.bluecircus.net.gif)
![[add to udn bookmark]](http://bookmark.udn.com/html/help/80_20_02.gif)

2007 年 六月 25日 於 7:53 pm
William 在 程式語言復習札記:null 判斷 一文中提到各種語言判斷 null 的方式.
文中幾種語言於公於私我大概都有使用過, 唯獨 Ruby [...]
2007 年 七月 12日 於 6:35 am
{ JavaScript的null判斷 }
寫了一些 test case 幫助釐清 [...]
2007 年 八月 2日 於 2:20 pm
查了一下,php 的 isset 在變數設為 NULL 時也會 return FALSE。