James Mitchell James Mitchell - 26 days ago 12
C Question

C Function to return char gives conflicting types error

I'm new to C and wrote the following code that returns a char.

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

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


But I get the following error when compiling:

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();
^


Any ideas? Does this require memory allocation? If so, why?

Answer Source

It is because you either have to define the function prototype above the main, or move the function above the main.

char test();

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

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

or

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

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