簡體   English   中英

C返回char的函數給出了沖突類型錯誤

[英]C Function to return char gives conflicting types error

我是C的新手並編寫了以下代碼來返回一個char。

int main(int argc, char * argv[]){
   char c = test();
   printf("num = %c \n", c);
}

char test(){
   char c = 'z';
   return c;
}

但編譯時出現以下錯誤:

read.c:8:1: warning: data definition has no type or storage class [enabled by default]
 test();
 ^
read.c:71:6: error: conflicting types for ‘test’
 char test(){
      ^
read.c:8:1: note: previous declaration of ‘test’ was here
 test();
 ^

有任何想法嗎? 這需要內存分配嗎? 如果是這樣,為什么?

這是因為你要么必須在main之上定義函數原型,要么將函數移到main之上。

char test();

int main(int argc, char * argv[]){
   char c = test();
   printf("num = %c \n", c);
}

char test(){
   char c = 'z';
   return c;
}

要么

char test(){
   char c = 'z';
   return c;
}

int main(int argc, char * argv[]){
   char c = test();
   printf("num = %c \n", c);
}

您在聲明之前調用test 要么在main函數之前聲明它,要么提供它的原型:

/* Prototype of test */
char test();

int main(int argc, char * argv[]) {
   char c = test();
   printf("num = %c \n", c);
}

char test() {
   char c = 'z';
   return c;
}

main()調用它時,您還沒有為test()函數提供原型。 要么做char test(void); 在源文件的頂部(或更常規地在頭文件中)。

其他選項是將test()的定義移到main()函數之上 ,這將確保定義本身提供原型。

錯誤的原因:

 error: conflicting types for ‘test’

就是在C99之前的C中,編譯器隱式地為test()提供了一個int返回原型(稱為隱式int規則 ),它與test()的實際定義沖突(其中它實際上有char作為返回類型)。 請注意,這不再有效(在C99及更高版本中)。

在C語言中,編譯器從頂部到底部開始“讀取”代碼,因此當它在主函數上試圖弄清楚什么是test()時,它還不知道這個函數。 要解決它,你可以把你的主函數放在test()函數之后,或者使用函數原型,這是更好的代碼實踐,manly用於將來的代碼讀取。 像這樣:

char test();

int main(int argc, char * argv[]){
   char c = test();
   printf("num = %c \n", c);
}

char test(){
   char c = 'z';
   return c;
}

在此聲明中使用名稱test之前

char c = test();

必須申報。

而這條消息

read.c:8:1: warning: data definition has no type or storage class [enabled by default]
 test();
 ^

表示編譯器不知道變量c的聲明中使用的表達式test()的類型作為初始化器。

為了與舊版本的C標准兼容,編譯器假定該函數的返回類型為int 然而,它遇到該函數具有返回類型char 這些編譯器消息說明了這一點

read.c:71:6: error: conflicting types for ‘test’
 char test(){
      ^
read.c:8:1: note: previous declaration of ‘test’ was here
 test();
 ^

所以在使用函數之前你必須聲明它

char test( void );

注意功能main的參數

int main(int argc, char * argv[]){

沒用過。 所以函數main可以聲明為

int main( void ){

所以程序看起來像

#include <stdio.h>

char test( void );

int main( void ) 
{
    char c = test();
    printf( "num = %c\n", c );

    return 0;
}

char test( void )
{
    char c = 'z';

    return c;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM