我有这个小代码来演示它:
#include "stdio.h"
int main() {
int a = testfunc(); // declared later
printf("%d", a);
return 0;
}
int testfunc() {
return 1;
}
它编译没有错误,并且1按预期输出。
查看实际操作:http: //ideone.com/WRF94E
为什么没有错误?它是 C 规范的一部分还是与编译器相关的东西?
我有这个小代码来演示它:
#include "stdio.h"
int main() {
int a = testfunc(); // declared later
printf("%d", a);
return 0;
}
int testfunc() {
return 1;
}
它编译没有错误,并且1按预期输出。
查看实际操作:http: //ideone.com/WRF94E
为什么没有错误?它是 C 规范的一部分还是与编译器相关的东西?
函数 testfunc() 是隐式声明的。编译器无法进行任何签名检查,因此如果您未能正确调用它,您可能会收到运行时错误。
这是 C 规范的一部分。但是 C 规范中的建议是在当前文件的开头或头文件中声明您计划实现和使用的所有函数。
因为,默认情况下,编译器将未声明的函数视为
int function_name ();
在内部,未声明的函数被视为返回类型为 int 并接受任意数量的参数。它也与您的实际函数匹配。所以没问题。
这取决于编译器。一些编译器会发出错误,其他的 - 一个警告,而其他的 - 什么都没有。编译器的职责只是检查您使用的函数是否具有正确的参数。如果你不声明它,那么编译器就不能检查和警告你滥用函数,但它可以生成调用函数的代码。另一方面,链接器的职责是查看函数是否已实现,并将其地址放入编译器先前生成的调用中。由于您的功能已实现,因此链接器可以正常工作。
由于您的编译器不会检查您,您可以尝试使用参数调用您的函数。该调用可能有效,但也可能使您的程序崩溃。
int a = testfunc();
int testfunc() {
return 1;
}
您没有收到任何错误,因为在 C 中默认函数签名是相同的。
如果你想让编译器告诉你看下面的演示:
像这样在没有前向声明的情况下调用,看看编译器会给你错误。
int a=testfunc(5.4);
int testfunc(float f)
{
return 1;
}
注意:C 中的最佳实践是提供forward declaration您将在程序中使用的函数。
编译器不需要查看函数定义来调用它,它只需要一个原型来检查参数,如果没有,编译器将假定函数返回int并且你知道你在做什么。但是,在链接时,如果链接器无法解析符号,那么您将收到错误消息。
In ANSI C, you do not have to declare a function prototype; however, it is a best practice to use them. If you do not have a prototype, and you call a function, the compiler will infer a prototype from the parameters you pass to the function.The compiler assumes that it has an int return type. If you declare the function later in the same compilation unit with a different return type, you'll get a compile error.