Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> การเขียนโปรแกรม C

ทำไม NULL pointer ถูกนิยามต่างกันใน C และ C++


ใน C++ null pointer สามารถนิยามได้โดย integer constant expression ที่มีค่า 0 เช่น

int* p = 0;

แต่ใน C null pointer นิยามได้โดย integer constant expression ค่า 0 หรือ cast เป็น void* เช่น

int* p = 0;

หรือ

int* p = (void*) 0;

ใน C++11 ใช้คีย์เวิร์ด "nullptr" แทน null pointer

int* ptr = nullptr;

ใน C

ตัวอย่าง

#include <stdio.h> int main() { int *p = 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; cout<<"The value of pointer is "; cout<<p; return 0; }

ผลลัพธ์

The value of pointer is 0.