[心得] 空指標常數(null pointer constant)

作者: wtchen (沒有存在感的人)   2016-04-28 02:51:03
以下是板工的小小心得,準備補充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)
作者: Feis (永遠睡不著 @@)   2016-04-28 04:03:00
...
作者: Frozenmouse (*冰之鼠*)   2016-04-28 10:22:00
應該是「賦值給」吧?這樣寫好像常數是lvalue一樣簡單來說C的標準就是定義了n和(void*)n為空指標常數的特例,其中n是值為0的integer const expr(void*)(void*)0會掛的真正原因是(void*)0的結果不是int const expr,所以整個結果非null ptr const你舉的例子是不是有搞錯lvalue和rvalue的方向…
作者: yvb   2016-04-28 18:12:00
func c = (void *)(void *)0; // C跟C++都看不懂 ???C 應該沒問題吧??
作者: Frozenmouse (*冰之鼠*)   2016-04-28 18:26:00
它是 "can only be assigned to" 被動式別拆開啊Orz不過這個已經不是程式問題了(炸

Links booklink

Contact Us: admin [ a t ] ucptt.com