[心得] 空指標常數(null pointer constant)
以下是板工的小小心得,準備補充13誡用。
若是有不對的地方,請各位鞭小力點 /(_ _)\
(板工很懶得上色,以後會放一份在板工新blog)
### 在C的情況(注意:C++不適用,C++的場合請看下一節) ###
根據C11 standard 6.3.2.3 裡對空指標常數 (null pointer constant)的定義:
An integer constant expression with the value 0, or such an expression cast
to type void *, is called a null pointer constant.
也就是說,(void*)0 是空指標常數(null pointer constant),
而(int *)0 是型別為整數指標的空指標(null pointer),這兩者是不一樣的。
比較明顯的分別是,空指標常數可以被設成任何型別指標的左值,
而空指標只能被設成同樣型別指標的左值。
以下是一個比較清楚的例子:
int *a = 0; // 沒問題,空指標常數
int *b = (int*) 0; // 沒問題,左值是同型別的空指標
int *c = (void*) 0; // C沒問題,左值是空指標常數,不過C++會掛
int *d = (long*) 0; // 爆了,左值跟右值不同型態
這邊有另一個例子:
typedef void (*func)(void); // func f = void (*f)();
func a = 0; // 沒事,a是空指標常數
func b = (void *)0; // C 沒問題,C++會掛
func c = (void *)(void *)0; // C跟C++都看不懂
### 在C++的情況 ###
根據C++14 standard 4.10 裡對空指標常數 (null pointer constant)的定義:
A null pointer constant is an integer literal (2.13.2) with value zero
**or**(以後為C++11後特有) a prvalue of type std::nullptr_t.
意思是說,它可以是0或 nullptr,所以以下的情況:
int x = NULL; // C++ 可能沒問題(視版本而定),不過會造成誤解
int* ptr = (void*)0; // C 沒問題,C++會掛
int* ptr = nullptr; // C++11以後的正統用法,
也就是上述C++14 standard裡的空指標常數
**int x = NULL** 為啥會在C++裡造成誤解?
因為C++有C沒有的函數重載(function overloading),舉例來說
void DoSomething(int x);
void DoSomething(char* x);
- NULL = 0: DoSomething(NULL)會呼叫void DoSomething(int x),即
DoSomething(0)。
- NULL=nullptr: 會呼叫void DoSomething(char* x),即DoSomething(nullptr)。
結論就是,C++11以後還是儘量用nullptr取代NULL吧!
### 參考資料 ###
- [comp.lang.c FAQ list · Question 5.2 ](http://c-faq.com/null/null2.html)
- [Is (int *)0 a null pointer?]
(http://stackoverflow.com/questions/21386995/is-int-0-a-null-pointer)
- [Why are NULL pointers defined differently in C and C++?]
(http://stackoverflow.com/questions/7016861/
why-are-null-pointers-defined-differently-in-c-and-c)
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 86.209.161.140
※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1461783066.A.60F.html
※ 編輯: wtchen (86.209.161.140), 04/28/2016 03:49:36
※ 編輯: wtchen (86.209.161.140), 04/28/2016 03:51:00
※ 編輯: wtchen (86.209.161.140), 04/28/2016 03:51:24
→
04/28 04:03, , 1F
04/28 04:03, 1F
推
04/28 10:22, , 2F
04/28 10:22, 2F
推
04/28 10:34, , 3F
04/28 10:34, 3F
→
04/28 10:34, , 4F
04/28 10:34, 4F
→
04/28 10:36, , 5F
04/28 10:36, 5F
→
04/28 10:36, , 6F
04/28 10:36, 6F
→
04/28 10:38, , 7F
04/28 10:38, 7F
我沒有,我只是想表達"assign to lvalue..." (中文不夠好阿)
不過說實話,我情願多發點心得文一邊被鞭一邊修正,
這樣自己學到東西別人可能也受益,
總比死抱著錯誤觀念來的好....
※ 編輯: wtchen (86.209.161.140), 04/28/2016 17:57:53
推
04/28 18:12, , 8F
04/28 18:12, 8F
→
04/28 18:13, , 9F
04/28 18:13, 9F
推
04/28 18:26, , 10F
04/28 18:26, 10F
→
04/28 18:26, , 11F
04/28 18:26, 11F
修正版出爐囉,請繼續幫忙找碴 XD
※ 編輯: wtchen (86.209.161.140), 04/28/2016 18:54:02
討論串 (同標題文章)
以下文章回應了本文:
完整討論串 (本文為第 1 之 2 篇):