let me explain commenting the original code you pasted :)
#include <stdio.h>
void bar(); //so, we declared bar here, thus it will be called successfully later
int main()
{
void foo(); //we declared foo here, thus the foo two statements below also can be called
printf("1 ");
foo(); //this works because the void foo(); some lines above
bar(); //this works because of bar() outside the main()
}
void foo() //here foo is defined
{
printf("2 ");
}
void bar() //here bar is defined
{
foo(); //this works because foo was declared previously
}
Indeed, you are both right, and wrong, right in the sense that the first declaration of foo() goes out of scope after main ends. Wrong in the sense that the linker would confuse stuff, the linker, that decides what function call calls what, can find the foo outside the main and figure that is the same foo declared inside the main.
That said, you should not declare functions inside other functions...
Also here is a better proof of what you want to know:
I tried to compile this:
#include <stdio.h>
void bar();
void bar()
{
void foo();
foo();
}
int main()
{
printf("1 ");
foo(); //line 18
bar();
}
void foo()
{
printf("2 ");
}
It gave me this error: prog.c:18:9: error: implicit declaration of function ‘foo’ [-Werror=implicit-function-declaration]
This is because the foo() inside bar() is valid, but the foo() on main is not, because although foo() is declared before main, it is still valid only inside bar()
bar()abovefoo()and try again.