I know that in our modern world NULL and 0 are not best practices in operating with pointers, and according to cppreference:
Pointer conversions A null pointer constant (see NULL), can be converted to any pointer type, and the result is the null pointer value of that type. Such conversion (known as null pointer conversion) is allowed to convert to a cv-qualified type as a single conversion, that is, it's not considered a combination of numeric and qualifying conversions.
But why this code is not allowed and gcc with clang give me an error?
A* foo()
{
return (bar(), NULL);
}
error: invalid conversion from long int to A*
The issue here is that
is an expression using the comma operator.
So the type of
(bar(), NULL)
is being determined as along int
as that is the type ofNULL
So it is trying to convert along int
with the value ofNULL
to anA*
which will fail.If we changed the code to
This will compile as the value of
NULL
is used and the value ofNULL
can be assigned to a pointer.The answer is presented in your question.
NULL
is constant,bar(), 0
is not constant.Just compare:
versus
versus