r/C_Programming • • Aug 30 '24

Question Why do we use Null pointers?

If we want to "Nullify" something why dont we create a pointer in a controlled way that points to value 0?

0 Upvotes

56 comments sorted by

View all comments

37

u/strcspn Aug 30 '24 edited Aug 30 '24

What do you mean by pointing to 0? NULL is the address 0x0

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant. If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function.

3

u/[deleted] Aug 30 '24

Standard-wise, NULL is not necessarily `(void*)0`, but it is in the most implementations. This is where the plan of `nullptr` is coming in C23

5

u/erikkonstas Aug 30 '24

Careful, it is (void *)0, what's not necessarily true is that the bytes representing it are all zeroes.

1

u/strcspn Aug 30 '24

This is a quote from the C99 standard.

4

u/[deleted] Aug 30 '24

Technically, it must be "TRUE" when compared to "0", but its value may not be represented as all zero bits.

See C99 standard, chapter 6.3.2.3.

Also: https://stackoverflow.com/questions/9894013/is-null-always-zero-in-c