C/CPP系類知識 What happens when a function is called before its declaration in C? 在C中當使用沒有聲明的函數時將發生什麼

來源:互聯網
上載者:User

標籤:

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中當使用沒有聲明的函數時將發生什麼

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.