c - 为什么在使用 int 变量时会收到警告,而在使用整数常量时却不会?

标签 c null integer language-lawyer constants

我有一段代码的两个版本。第一种是使用 int变量作为条件测试表达式的一部分,第二个使用整数常量表示相同 - 两者都表示相同的整数值 - 24 .
1. code :

#include <stdio.h>

int main()
{
    int var = 24;

    if((!var) == NULL)
    {
        printf("1");
    }
}
2. code :
#include <stdio.h>

int main()
{
    if((!24) == NULL)
    {
        printf("1");
    }
}

当我尝试编译第一个版本时,收到警告:

warning: comparison between pointer and integer


来自 gcc,和

warning: comparison between pointer and integer ('int' and 'void *') [-Wpointer-integer-compare]


从叮当。
当我使用与整数常量相同的值编译几乎等效的代码时,一切都很好。为什么?

到目前为止我的研究:
我查看了 C18 并在第 6.4.4 节“常量”中找到:
首先在小节/2 和/3 下:

"2 - Each constant shall have a type and the value of a constant shall be in the range of representable values for its type."

"3 - Each constant has a type, determined by its form and value, as detailed later.".


第/5 小节下的第二个:

"The type of an integer constant is the first of the corresponding list in which its value can be represented."


以下列表:
list
因此,一个没有后缀且相对于 24 的可表示值的整数常量应该有类型 int .

我了解警告本身并知道 NULL通常在大多数实现中扩展为 (void*) 0 .因此,抛出此警告是合理的。
但是为什么在使用与整数常量相同的值时不会出现警告?

最佳答案

从 C11 6.3.2.3/3:

An integer constant expression with the value 0, or such an expression cast to type void *, is called a null pointer constant.



从 6.5.9/2 关于相等运算符 ==!= :

One of the following shall hold:
...
— one operand is a pointer and the other is a null pointer constant.



请注意,整数常量表达式不限于整数常量(0、42 等),还可以包括作用于它们的运算符,如 5+5-10 .
!24是值为 0 的整数常量表达式,因此计为空指针常量。 ==允许操作符在指针和空指针常量之间起作用,这使得 (!24) == NULL一个有效的比较。

在您的第一个示例中,!var不是整数常量表达式,因为它包含变量操作数,因此不能与指针进行比较。

警告:在大多数实现中,NULL定义为 (void*)0以上是正确的。但是,标准允许将其定义为任何空指针常量,例如 0 .如果是这种情况,则比较(!var) == NULL将编译,因为它与 (!var) == 0 相同.

关于c - 为什么在使用 int 变量时会收到警告,而在使用整数常量时却不会?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60623739/

相关文章:

c - 将链表作为参数传递时出错

c++ - 将菜单栏添加到 QT cvNameWIndow

c - 在 C 中格式化文本

c# - 我不能让空值使我的 C# 程序崩溃?

python - 在 Python 中取 int 的 2 次方模数的首选方法是什么

mysql - 在 mysql 中创建序列号的自定义格式示例

c - 使用 sscanf 从 C 中的字符串常量中读取单个字符

swift - PageViewController 不适用于 Swift 2.0

android - IllegalArgumentException:指定为非null的参数为null

javascript - 我想打印总是减去 3 的整数