该标准说:
"An integer constant expression with the value 0, or such an expression cast to type
void*
, is called a null pointer constant.67) 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."
"67) The macro NULL is defined in stddef.h (and other headers) as a null pointer constant; see 7.19."
Source: ISO/IEC 9899:2018 (C18), §6.2.3.2/3 "Pointers".
当然,最常见的空指针常量是
0
和(void*) 0
,大多数实现将它们用作空指针常量,但作为标准指令,必须遵循-“值0 的整数常量表达式,或此类类型转换为void*
类型的表达式”-空指针常量也应为以下任意值:1 * 0
0 * 0
0 - 0
25 - 25
(-4) + (4)
(0 * ((0 * 25) * 3)
(0) * (-100)
就像他们的任何吊坠之前带有
(void*)
一样,f.e。 (void*) (1 * 0)
或(void*) (25 - 25)
。以及 bool 表达式:
(void*) ((1 + 1) == 25)
(void*) !(9)
因此,任何类似于以下之一的语句:
int* ptr = 25 - 25;
int* ptr = (void*) ((-4) + 4);
int* ptr = (0 * ((0 * 25) * 3);
int* ptr = (void*) !(9);
int* ptr = ((1 + 1) == 25);
按照标准,应使
ptr
为空指针。我正在寻找使本论文无效的C标准的任何部分。
据我搜索,在Stack Overflow上不应重复出现此问题。
最佳答案
您是正确的,所有这些都是有效的。
C standard的6.6节规定:
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.
您示例中的每个表达式均符合以下说明,即:
因此,所有方法都是将
NULL
分配给指针的有效方法。一些示例是而不是整数常量表达式:
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
关于空指针常量可以是任何取值为0的整数常量表达式吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61734858/