標籤:
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);}
輸出結果:
[email protected]:~/myProg/geeks4geeks/cpp$ ./a.out 1954607895[email protected]:~/myProg/geeks4geeks/cpp$ ./a.out 1943297623[email protected]:~/myProg/geeks4geeks/cpp$ ./a.out -16827881[email protected]:~/myProg/geeks4geeks/cpp$ ./a.out 67047927[email protected]:~/myProg/geeks4geeks/cpp$ ./a.out -354871129[email protected]:~/myProg/geeks4geeks/cpp$ ./a.out -562983177[email protected]:~/myProg/geeks4geeks/cpp$ ./a.out 33844135[email protected]:~/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).
C/CPP系類知識 What happens when a function is called before its declaration in C? 在C中當使用沒有聲明的函數時將發生什麼