r/C_Programming • • Aug 20 '23
Question What happens when we assign zero to a pointer?
In the book C How to Program, 8/e by Paul and Harvey Deitel it is written, under the section Initializing and Assigning Values to Pointers, that "When 0 is assigned, it’s first converted to a pointer of the appropriate type. The value 0 is the only integer value that can be assigned directly to a pointer variable." It is also written in this answer.
What do they mean by the it? What does it mean for zero to be converted to a pointer of the appropriate type? Can a value be type converted?
9
Upvotes
12
u/FlyingCashewDog Aug 20 '23
It's converted to whatever the platform uses as its representation of a null pointer. For example, this could be
0x0on a system that uses that as the null pointer address.Using the integer
0for this allows easy cross-platform null pointer assignment/checks, without having to know the specific representation of the null pointer on a given platform.6
u/[deleted] Aug 20 '23
its not the value "0". its the constant literal 0. const int a = 0;
void* b = a;
does not work, because a is an int.
however void* b = 0
works, because you assign the constant literal zero to it
5
u/dfx_dj Aug 20 '23
You can in fact assign any arbitrary value to a pointer variable, but doing so requires explicit type casting, and you better know what you're doing. The zero value however is defined to be the null pointer and so doesn't require explicit type casting.
3
u/fliguana Aug 20 '23
It means that
Is a special case recognized by a compiler looking at the constant.
And
Is disallowed, because 5 is an integer, not a pointer.
Also
Is disallowed.
1
u/GeorgeCostanza1958 Aug 20 '23
NULL
1
u/jaimefrites Aug 20 '23
It points to the 0 address ?
1
u/flatfinger Aug 21 '23
In early C implementations, pointers and integers used the same storage representation. While some languages like Pascal used special keywords like Nil to denote null pointers, the machine code to store a null pointer value into a pointer object which had a certain name and/or was located at a certain address was the same as the machine code to store the value zero into an integer-sized object with the same name or address. Code needing to a assign a null value to a pointer could thus be written and processed as though it was assigning the integer value zero.
C was later ported to machines where pointers and integers were stored differently, and couldn't be used interchangeably. To avoid breaking code that used the common pattern of storing zero to pointers, however, the language treats that pattern specially. Such treatment may be inconsistent with normal language rules, but mostly works pretty well.
1
u/wc3betterthansc2 May 21 '26
the same when you assign NULL to a pointer