Can a null pointer constant be any integer constant expression evaluated to 0?
Yep.
[C99 6.6/6]:
An integer constant expression shall have integer type and shall only have operands that are integer constants, enumeration constants, character constants, sizeof expressions whose results are integer constants, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to the sizeof operator.
Note that this is not the case in C++, where null pointer constants are defined differently:
[conv.ptr]/1:
A null pointer constant is an integer literal ([lex.icon]) with value zero or a prvalue of typestd::nullptr_t
. [..]
You are correct that all of these are valid.
Section 6.6 of the C standard states:
1
constant-expression: conditional-expression
...
3 Constant expressions shall not contain assignment, increment, decrement, function-call,or comma operators, except when they are contained within a subexpression that is not evaluated.
...
6 An integer constant expression shall have integer type and shall only have operands that are integer constants,
enumeration constants, character constants,sizeof
expressions whose results are integer constants,_Alignof
expressions, and floating constants that are the immediate operands of casts. Cast operators in an integer constant expression shall only convert arithmetic types to integer types, except as part of an operand to thesizeof
or_Alignof
operator.
Each of the expressions in your examples fit this description, i.e.:
- All operands are integer constants
- The expression is a conditional-expression (i.e. doesn't use assignment or comma operators) with no increment, decrement, or function call operators
- Evaluates to 0
So all are valid ways to assign NULL
to a pointer.
Some examples that are not integer constant expressions:
int x = 1;
int *ptr1 = (3, 0); // invalid, comma operator not allowed
int *ptr2 = (x = 0); // invalid, assignment not allowed
int *ptr3 = x - 1; // invalid, an operand is not an integer constant