gpt4 book ai didi

在 C++ 中将 NULL 转换为 void

转载 作者:行者123 更新时间:2023-12-01 12:56:32 25 4
gpt4 key购买 nike

我遇到了一个令人费解的符号:

if(ptr != (void)(NULL)) {
//some action
}

所以它扩展到
if(ptr != (void)((void *)0)) {
//some action
}

这至少看起来很奇怪。
这背后真的有任何理由吗,或者它只是毫无意义,甚至是错误的?不过,它编译得很好(在 linux/gcc 上,不记得版本了)。

-编辑-

我今天检查了该代码,这是新信息:
首先,类型转换被用在一个宏中,它扩展到
return (void)((void*)0);

在返回 void 的函数中。
代码使用 gcc (GCC) 4.1.2 20080704 on (Red Hat 4.1.2-50) 编译。
那么,这个语句是否等价于
return void;

这相当于
return;

或者还有更多的东西吗?

最佳答案

它可能应该是一个空指针的强制转换,它与“指针”相同(即指向任何类型的指针):

if (ptr != (void *)(NULL)) {
...
}

虽然类型转换是不必要的:
if (ptr != NULL) {
...
}

您的代码甚至无法在我的系统上编译(带有 GCC 4.2.1 的 Mac),GCC 报告的错误消息是 void value not ignored as it ought to be .这是意料之中的,因为 void意味着根本没有值/类型,您无法将其与其他任何内容进行比较。

这是 C99 标准所说的:

§6.3.2.2 void

1 The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way, and implicit or explicit conversions (except to void) shall not be applied to such an expression. If an expression of any other type is evaluated as a void expression, its value or designator is discarded. (A void expression is evaluated for its side effects.)

§6.5.9 Equality operators

Constraints

2 One of the following shall hold:

  • both operands have arithmetic type;
  • both operands are pointers to qualified or unqualified versions of compatible types;
  • one operand is a pointer to an object or incomplete type and the other is a pointer to a qualified or unqualified version of void; or
  • one operand is a pointer and the other is a null pointer constant.


§6.3.2.2 已经禁止使用 void ,第 6.5.9 节中的约束也将被违反。

因此,如果编译器允许 ptr != (void)(NULL)那么它就会违反 C99 标准。它可能只是旧 GCC 版本的错误或错误。

我只找到了 C89 的草稿,这里是 void部分几乎与 C99 中的相同。但是关于相等运算符的部分让我摸不着头脑。似乎允许与 void 进行比较,但这可能是草稿中的错误或措辞问题:

§3.2.2.2 void

The (nonexistent) value of a void expression (an expression that has type void) shall not be used in any way, and implicit or explicit conversions (except to void ) shall not be applied to such an expression. If an expression of any other type occurs in a context where a void expression is required, its value or designator is discarded. (A void expression is evaluated for its side effects.)

§3.3.9 Equality operators

Constraints

One of the following shall hold:

  • both operands have arithmetic type;
  • both operands are pointers to qualified or unqualified versions of compatible types;
  • one operand is a pointer to an object or incomplete type and the other is a qualified or unqualified version of void ; or
  • one operand is a pointer and the other is a null pointer constant.

关于在 C++ 中将 NULL 转换为 void,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9539607/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com