Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why C++ compiler allows assigning 0 to pointers and no other number [duplicate]

Tags:

c++

I was posting an answer to a question - and commenting it occured to me, thanks to another poster by the name metal that

C++ compiler allowed this:

int *p = 0; but not this int *p = 1. Is 0 considered a special number?

Edit: @DavidHefferman said Is 0 special? In the context of a pointer, yes it is. - why?

like image 332
Aniket Inge Avatar asked Oct 17 '25 19:10

Aniket Inge


2 Answers

Section 4.10 of the standard, Pointer conversions [conv.ptr] says:

A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zero or a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the result is the null pointer value of that type and is distinguishable from every other value of pointer to object or pointer to function type. Such a conversion is called a null pointer conversion. Two null pointer values of the same type shall compare equal. The conversion of a null pointer constant to a pointer to cv-qualified type is a single conversion, and not the sequence of a pointer conversion followed by a qualification conversion (4.4). A null pointer constant of integral type can be converted to a prvalue of type std::nullptr_t.

So, yes, 0 is a special value in the context of pointers.

like image 166
David Heffernan Avatar answered Oct 20 '25 08:10

David Heffernan


0 is NULL, while 1 is an invalid address.

like image 23
TieDad Avatar answered Oct 20 '25 10:10

TieDad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!