[C/CPP系列知识] 在C中使用没有声明的函数时将发生什么 What happens when a function is called before its declaration in C
http://www.geeksforgeeks.org/g-fact-95/
1 在C语言中,如果函数在声明之前被调用,那么编译器假设函数的返回值的类型为INT型,
所以下面的code将无法通过编译:
#include <stdio.h> int main(void) { // Note that fun() is not declared printf("%d\n", fun()); return 0; } char fun() { return 'G'; }
错误:其实就是fun函数定义了两遍,冲突了
test1.c:9:6: error: conflicting types for 'fun' char fun() ^ test1.c:5:20: note: previous implicit declaration of 'fun' was here printf("%d\n", fun()); ^
将返回值改成int行可以编译并运行:
#include <stdio.h> int main(void) { printf("%d\n", fun()); return 0; } int fun() { return 10; }
2 在C语言中,如果函数在声明之前被调用,如果对函数的参数做检测?
compiler assumes nothing about parameters. Therefore, the compiler will not be able to perform compile-time checking of argument types and arity when the function is applied to some arguments. This can cause problems.
编译器对参数不做任何假设,所以无法做类型检查。 下面code就会有问题,输出是garbage
#include <stdio.h> int main (void) { printf("%d", sum(10, 5)); return 0; } int sum (int b, int c, int a) { return (a+b+c); }
输出结果:
diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 1954607895 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 1943297623 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out -16827881 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 67047927 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out -354871129 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out -562983177 diego@ubuntu:~/myProg/geeks4geeks/cpp$ ./a.out 33844135 diego@ubuntu:~/myProg/geeks4geeks/cpp$
所以It is always recommended to declare a function before its use so that we don’t see any surprises when the program is run (See this for more details).