gpt4 book ai didi

c++ - 无效* p ...; if (p > 0) .... 这是未定义的行为吗?

转载 作者:搜寻专家 更新时间:2023-10-30 23:57:49 25 4
gpt4 key购买 nike

我在编译器升级后遇到了新的警告消息。

warning: ordered comparison of pointer with integer zero [-Wextra]

    if (inx > 0)

事实证明,inx 是一个指针。通常我希望看到这个旧代码与 0 或 NULL 进行比较。这让我开始思考有符号和无符号的值,以及可能的风险。

一些研究表明:

这些似乎表明地址(由 malloc 返回)永远不能为零

这把我带到了我的旧标准拷贝。

4.10 Pointer conversions

1 A null pointer constant is an integral constant expression (5.19) prvalue of integer type that evaluates to zeroor a prvalue of type std::nullptr_t. A null pointer constant can be converted to a pointer type; the resultis the null pointer value of that type and is distinguishable from every other value of pointer to object orpointer to function type. Such a conversion is called a null pointer conversion. Two null pointer values of thesame type shall compare equal. The conversion of a null pointer constant to a pointer to cv-qualified type isa single conversion, and not the sequence of a pointer conversion followed by a qualification conversion (4.4).A null pointer constant of integral type can be converted to a prvalue of type std::nullptr_t.

它特别指出两个空指针比较相等。

考虑到这一点,那一小段代码是未定义的行为吗?还是我遗漏了另一 block 拼图?

最佳答案

这不是未定义的行为,但如果 inx 则结果未指定不为空。

C++11 5.9/2: If two pointers p and q of the same type point to different objects that are not members of the same object or elements of the same array or to different functions, or if only one of them is null, the results of p<q, p>q, p<=q, and p>=q are unspecified.

因此您可以确定条件代码不会在inx 时执行。为空 - 但如果它不为空则不会。比较应该是inx != 0 ,当且仅当 inx 时,它被明确定义为 true是非空的。

关于c++ - 无效* p ...; if (p > 0) .... 这是未定义的行为吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23200872/

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