gpt4 book ai didi

c - 在c中声明没有任何数据类型的变量

转载 作者:太空狗 更新时间:2023-10-29 16:24:52 25 4
gpt4 key购买 nike

在这个c程序中

a=8;
main()
{
printf("%d", a);
}

变量 a 已在没有任何数据类型的情况下声明,但该程序仍能成功编译并提供所需的输出。
输出::

8  

查看ideone .
但是,当我在 main 中声明相同的变量时,它会出现编译错误。

main()
{
a=8;
printf("%d", a);
}

输出::

prog.c:2: warning: return type defaults to ‘int’
prog.c: In function ‘main’:
prog.c:3: error: ‘a’ undeclared (first use in this function)
prog.c:3: error: (Each undeclared identifier is reported only once
prog.c:3: error: for each function it appears in.)
prog.c:4: warning: implicit declaration of function ‘printf’
prog.c:4: warning: incompatible implicit declaration of built-in function ‘printf’

参见 here .

第一个程序如何运行,但第二个程序如何运行?

最佳答案

你在这里看到的是 "Implicit Int Rule" 在工作中。简单地说规则说:

"A variable declared without an explicit type name is assumed to be of type int."

请注意,此规则在 c99 标准[引用 1] 中已被撤销。但是,根据您的编译器及其设置,第一个示例可能会编译并出现警告,或者将无法编译( 具有严格的编译设置)

如果您使用符合 c99 标准的严格设置编译您的第一个示例,编译器会告诉您根本原因。

检查 here .

cc1: warnings being treated as errors
prog.c:1: error: data definition has no type or storage class
prog.c:1: error: type defaults to ‘int’ in declaration of ‘a’
prog.c:3: error: return type defaults to ‘int’
prog.c: In function ‘main’:
prog.c:4: error: implicit declaration of function ‘printf’
prog.c:4: error: incompatible implicit declaration of built-in function ‘printf’

编辑:

why does the first example work but second does not?

请注意规则中对“变量声明”一词的强调。

在第一个示例中,由于语句在全局范围内,它被视为隐式声明隐式 Int 规则得到应用于它。

在第二个示例中,声明作为赋值而不是声明。由于没有声明,隐式 int 规则 不适用于此处。在没有任何类型的情况下,编译器无法确定 a 的类型,因此会报告错误。


[引用 1]

C99 标准:前言
第 5 段:

This edition replaces the previous edition, ISO/IEC 9899:1990, as amended and corrected by ISO/IEC 9899/COR1:1994, ISO/IEC 9899/COR2:1995, and ISO/IEC 9899/AMD1:1995.
Major changes from the previous edition include:
.....
.....
— remove implicit int
.....
.....

关于c - 在c中声明没有任何数据类型的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11064292/

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