[英]Function header/declaration
這是我的主要功能,也是我要傳遞的內容。
int main(void){
struct can elC[7]; // Create an array of stucts
Initialize(elC); // initializes the array
return 0;
}
int Initialize(struct can elC[7]){
}
在C語言中,我們不必在main或其他東西之前聲明函數嗎? 如果是這樣,它將如何? 我的代碼運行良好,聲明為
int Initialize();
但是我不需要
int Initialize(struct can elc[7]);
/* Declaration of Structure */
struct can {
/* Structure members */
};
/* Function Prototype - ANY OF THE THREE */
int Initialize();
int Initialize(struct can []);
int Initialize(struct can var[]);
int main (void)
{
struct can elC[7]; // Create an array of stucts
Initialize(elC); // Call to function - Initializes the array
return 0;
}
int Initialize(struct can elC[7])
{
//Do something;
return 0;
}
如果不聲明原型會怎樣?
以下將正常工作。
$ gcc filename.c
當與-Wall
選項結合使用時,會發出警告。
$ gcc filename.c -Wall
In function ‘main’:
Warning: implicit declaration of function ‘Initialize’ [-Wimplicit-function-declaration]
因此,總是最好在main
之前聲明原型
int Initialize(struct can []);
要么
int Initialize(struct can var[]);
以下也是有效的,表示您可以傳遞任意數量的參數。 看這里 。
int Initialize();
在C89中,您不必在調用函數之前先聲明它; 但是,如果您確實調用了一個未聲明的函數,則就像您將該函數聲明為:
int funcname();
空括號並不表示該函數不帶參數。 這僅僅意味着我們的聲明不是原型 。 在此階段,參數的數量和類型是未知的(但它不是像printf()
這樣的帶有可變參數列表的printf()
因為即使在C89中,使用它們時,它們的作用域也必須是原型)。
如果實際函數返回的不是int
,或者使用錯誤的類型或數量的參數調用它,或者在應用默認參數提升后任何參數的類型不同,則調用該函數會導致未定義的行為。
您的代碼不會受到任何這些限制的影響,因此您的代碼在C89中是正確的。 但是,無論如何都使用函數原型被認為是一種很好的樣式,因為它使編譯器能夠檢測所有這些情況並報告錯誤。
在C99中,必須在調用函數之前先聲明它。 合適的原型將是:
int Initialize(struct can *elC);
如果您的編譯器支持,我也建議您使用C99或C11。 關於在功能參數列表中使用[]
, 請參見此處 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.