There are a few similar questions asking people to debug their code, where the compiler produces a warning of implicit declaration of functions. I know that this warning is produced because if a function is used without there being a prior declaration, function calls can be treated as implicit declarations.
This code has an intentional bug for educational purposes.
There are two implicitly declared functions here: one returns int
, the second function returns another data type which is char*
.
#include <stdio.h>
int main(void)
{
function1();
function2();
}
int function1(void)
{
printf("function1\n");
return 2;
}
char* function2(void)
{
char* word = "function2\n";
printf(word);
return word;
}
When I go to compile this code, I get these warnings, and an error:
$ gcc test1.c
test1.c: In function ‘main’:
test1.c:5:5: warning: implicit declaration of function ‘function1’ [-Wimplicit-function-declaration]
function1();
^
test1.c:6:5: warning: implicit declaration of function ‘function2’ [-Wimplicit-function-declaration]
function2();
^
test1.c: At top level:
test1.c:15:7: error: conflicting types for ‘function2’
char* function2(void)
^
test1.c:6:5: note: previous implicit declaration of ‘function2’ was here
function2();
^
First I created the function1
and I was able to compile and run the code without problems. The implicit declaration of int function1()
was accepted, even though the compiler produced some warnings.
Then I created the function2
and to my surprise, an error was produced by the compiler and the code rejected. Why was the implicit declaration of char* function2()
not accepted? Why didn't the function call as an implicit declaration work?
This is the error:
error: conflicting types for ‘function2’
What is the conflicting type? There is only one type. The function takes no arguments and returns char*
.
Why did it work for function1
?