gpt4 book ai didi

c - 为什么空声明适用于具有 int 参数的定义但不适用于 float 参数?

转载 作者:太空狗 更新时间:2023-10-29 16:40:22 26 4
gpt4 key购买 nike

我认为不同之处在于 declaration 没有参数类型...

为什么这样做:

int fuc();

int fuc(int i) {
printf("%d", i);
return 0;
}

但是编译失败:

int fuc();

int fuc(float f) {
printf("%f", f);
return 0;
}

消息:

error: conflicting types for ‘fuc’. note: an argument type that has a default promotion can’t match an empty parameter name list declaration

最佳答案

声明:

int f();

...告诉编译器一些标识符(f,在本例中)命名一个函数,并告诉它函数的返回类型——但不是 指定函数要接收的参数的数量或类型。

原型(prototype):

int f(int, char);

...在其他方面类似,但也指定了函数要接收的参数的数量/类型。如果它没有参数,您可以使用类似 int f(void) 的东西来指定它(因为将括号留空是一个声明)。一种新型的函数定义:

int f(int a, char b) { 
// do stuff here...
}

...也充当原型(prototype)。

如果范围内没有原型(prototype),编译器会在调用函数之前对参数应用默认提升。这意味着任何 charshort 都被提升为 int,任何 float 都被提升为 double 。因此,如果您声明(而不是原型(prototype))一个函数,您不想指定任何charshortfloat 参数——调用这样的东西会/会产生未定义的行为。使用默认标志,编译器可能会拒绝代码,因为基本上没有办法正确使用它。您也许可以找到一些编译器标志,使其接受代码,但这毫无意义,因为无论如何您都无法使用它...

关于c - 为什么空声明适用于具有 int 参数的定义但不适用于 float 参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5481579/

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