How is "int* ptr = int()" value initialization not illegal?
Solution 1:
int()
is a constant expression with a value of 0, so it's a valid way of producing a null pointer constant. Ultimately, it's just a slightly different way of saying int *ptr = NULL;
Solution 2:
Because int()
yields 0
, which is interchangeable with NULL
. NULL
itself is defined as 0
, unlike C's NULL
which is (void *) 0
.
Note that this would be an error:
int* ptr = int(5);
and this will still work:
int* ptr = int(0);
0
is a special constant value and as such it can be treated as a pointer value. Constant expressions that yield 0
, such as 1 - 1
are as well allowed as null-pointer constants.
Solution 3:
The expression int()
evaluates to a constant default-initialized integer, which is the value 0. That value is special: it is used to initialize a pointer to the NULL state.