gpt4 book ai didi

c - 在声明 `int foo() {}` 之后定义 `int foo(void) {}` 与 `int foo(void);`

转载 作者:行者123 更新时间:2023-12-03 23:49:00 24 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





func() vs func(void) in C99

(4 个回答)


2年前关闭。




注意:这与 func() vs func(void) in c99 不同。 , 因为这里的问题专门询问 实现 在有效 之后的零参数函数声明 .

如果零参数的实现包括 void关键词?具体来说,C标准对下面两个函数的实现有什么要说的吗?请注意, foo1foo2被声明为零参数函数 ;唯一的区别在于实现,而不是声明:

#include <stdio.h>

int foo1(void); // inform compiler that foo1 and foo2 are zero-args fns.
int foo2(void);

int main() {
printf("%d\n", foo1());
printf("%d\n", foo2());
return 0;
}

int foo1(void) { return 22; }
int foo2() { return 22; }

我注意到 gcc -Wall -std=c99 -Wpedantic foo.c -o foo编译和执行没有任何警告或错误,但是否有任何违反标准的行为?

最佳答案

您发布的代码是正确的。 int foo2(void);声明 foo2作为不带参数,并形成一个原型(prototype)。

函数定义必须与此兼容;并且带有空括号的定义与此原型(prototype)兼容。这是在 C11 6.7.6.3/15 中指定的,这是一口:

For two function types to be compatible, both shall specify compatible return types. Moreover, the parameter type lists, if both are present, shall agree in the number of parameters and in use of the ellipsis terminator; corresponding parameters shall have compatible types. If one type has a parameter type list and the other type is specified by a function declarator that is not part of a function definition and that contains an empty identifier list, the parameter list shall not have an ellipsis terminator and the type of each parameter shall be compatible with the type that results from the application of the default argument promotions. If one type has a parameter type list and the other type is specified by a function definition that contains a (possibly empty) identifier list, both shall agree in the number of parameters, and the type of each prototype parameter shall be compatible with the type that results from the application of the default argument promotions to the type of the corresponding identifier. (In the determination of type compatibility and of a composite type, each parameter declared with function or array type is taken as having the adjusted type and each parameter declared with qualified type is taken as having the unqualified version of its declared type.)



关于这一点有这么多文字的原因是C最初只有K&R风格的函数,然后添加了原型(prototype)。因此,必须有文字来涵盖 K&R 风格与原型(prototype)风格混合的所有可能组合。以我的粗体部分开头的部分是指当函数先前已使用原型(prototype)声明时使用 K&R 样式的函数定义。

同样相关:在 C11 (6.11.6) 中使用空括号已过时。

Certain features are obsolescent, which means that they may be considered for withdrawal in future revisions of this International Standard. They are retained because of their widespread use, but their use in new implementations or new programs is discouraged.

关于c - 在声明 `int foo() {}` 之后定义 `int foo(void) {}` 与 `int foo(void);`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60517172/

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