函数使用前需要声明吗?如果我们不使用函数声明而直接调用它,编译器会报错吗?请按照标准C回答。
如果是,那么如果未定义函数参数,则类型参数将转换为 int 并将 float 转换为 double 意味着什么?
最佳答案
在 ANSI C 中,您不必声明函数原型(prototype);但是,最好使用它们。该标准允许您不使用它们的唯一原因是为了向后兼容非常旧的代码。
如果您没有原型(prototype),并且调用函数,编译器将根据您传递给函数的参数推断原型(prototype)。如果您稍后在同一编译单元中声明该函数,并且该函数的签名与编译器猜测的不同,您将收到编译错误。
更糟糕的是,如果该函数位于另一个编译单元中,则无法获得编译错误,因为没有原型(prototype)就无法进行检查。在这种情况下,如果编译器出错,如果函数调用在堆栈上推送的类型与函数预期的类型不同,则可能会出现未定义的行为。
约定是始终在与包含该函数的源文件同名的头文件中声明原型(prototype)。
通过原型(prototype),编译器可以验证您是否正确调用了函数(使用正确数量和类型的参数)。
如果没有原型(prototype),也可能会出现这样的情况:
// file1.c
void doit(double d)
{
....
}
int sum(int a, int b, int c)
{
return a + b + c;
}
还有这个:
// file2.c
// In C, this is just a declaration and not a prototype
void doit();
int sum();
int main(int argc, char *argv[])
{
char idea[] = "use prototypes!";
// without the prototype, the compiler will pass a char *
// to a function that expects a double
doit(idea);
// and here without a prototype the compiler allows you to
// call a function that is expecting three argument with just
// one argument (in the calling function, args b and c will be
// random junk)
return sum(argc);
}
关于C 函数声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3086592/