空指针常量可以是任何取值为0的整数常量表达式吗?

标签 c pointers null language-lawyer constant-expression

该标准说:

"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 the sizeof or _Alignof operator.



    您示例中的每个表达式均符合以下说明,即:
  • 所有操作数都是整数常量
  • 表达式是一个条件表达式(即不使用赋值或逗号运算符),没有增量,减量或函数调用运算符
  • 评估为0

  • 因此,所有方法都是将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/

    相关文章:

    c - c中变量的声明和定义

    c - 反转字符串时获取 "Segmentation fault Core Dumped Error "

    java - 如何使方法采用空值?

    Mysql: CONCAT_WS ('' , col) vs (col 为空或 col=0)

    c - 如何通过将其元素放入c中的不同子集来组织数组?

    c - 如何在C中获取空输入或仅ENTER

    c - 我的代码有什么问题吗?解析输入文本文件 (C)

    c++ - 将指向数组数组的指针传递给函数

    C、函数格式化中的结构指针

    php - MySQL 复杂查询未返回正确结果