Reputation: 1113
#include <stdio.h>
int main()
{
void foo(), f();
f();
}
void foo()
{
printf("2 ");
}
void f()
{
printf("1 ");
foo();
}
Output:
1 2
How the declaration is working here? And if I define F() before foo() I am getting error.
Wrong!
#include <stdio.h>
int main()
{
void foo(), f();
f();
}
void f()
{
printf("1 ");
foo();
}
void foo()
{
printf("2 ");
}
ERROR
> main.c: In function 'f': main.c:21:13: error: incompatible implicit
> declaration of function 'foo'
> foo();
> ^ main.c:7:18: note: previous implicit declaration of 'foo' was here
> void foo(), f();
^
Why is this happening?
Upvotes: 1
Views: 2355
Reputation:
You can redeclare something as many times as you want as long as they have the exact same declaration. For example the following is valid:
void foo();
void foo();
void foo();
However, void foo();
and foo();
aren't the same. The latter implicitly defaults to int foo();
. This is why you need to define foo();
before you call it or it will get treated as a redeclaration/new declaration.
Upvotes: 0
Reputation: 46415
The error message my compiler gives is "implicit declaration".
You declared the functions f()
and foo()
as void
, in the scope of main. You then use them outside of that scope (namely, you call foo()
from inside f()
- and f
is declared outside of main
).
The compiler treats this encouter with foo();
in the second line of f()
as "the first time I heard of this function" - since it is no longer in the scope of main
, it has forgotten everything it was told while it was in the main
scope (including "the return type of foo()
and f()
will be void
). Absent any information, it will assume that foo()
returns an int
. When it finally comes across the definition of foo
, lower down in the code, it realizes that it was wrong about its assumption. But rather than quietly fixing it, it complains.
That's C for you.
If you put the declaration before main()
, your problem goes away:
#include <stdio.h>
void foo(), f();
int main(void)
{
f();
}
void f()
{
printf("1 ");
foo();
}
void foo()
{
printf("2 ");
}
Thus - the problem is not the "multiple declaration" of your function (as you implied in the title of your question) - it is the scope of the declaration that is causing trouble.
Upvotes: 2
Reputation: 8481
This is a matter of scope. In the first example, foo
and f
are known to main because you declared them. f()
knows foo
because it's declared before it.
In your second example, the declaration of f
and foo
being local to main, f()
doesn't know foo
because it wasn't declared before it.
Upvotes: 2
Reputation: 469
It's called "forward declaration". Check google for the details, but in your case:
void f();
void foo();
void f() { foo(); }
void foo() {}
int main { f(); return 0; }
Upvotes: 1