為什麼在 C 和 C++ 中對 NULL 指標的定義不同?
在 C++ 中,空指標可以透過空指標常量定義,空指標常量是值 0 的整型常量表達式,如 −
int*p = 0;
但在 C 語言中,空指標可以透過空指標常量定義,空指標常量是值 0 的整型常量表達式,或將這樣的表示式強制轉換為 void*,如 −
Int *p = 0;;
或
int*p = (void*) 0;
在 C++11 中,使用關鍵字“nullptr”表示空指標。
int* ptr = nullptr;
在 C 語言中
示例
#include <stdio.h> int main() { int *p= NULL; //initialize the pointer as null. printf("The value of pointer is %u",p); return 0; }
輸出
The value of pointer is 0.
在 C++ 中
示例
#include <iostream> using namespace std; int main() { int *p= NULL; //initialize the pointer as null. cout<<"The value of pointer is "; cout<<p; return 0; }
輸出
The value of pointer is 0.
廣告