i have read in various places that functions which are declared in main() cannot be called outside main. But in below program fun3() is declared inside main() and called outside main() in other functions, and IT WORKS, giving output 64.here's link http://code.geeksforgeeks.org/7EZZxQ .however,if i change fun3() return type int to void ,it fails to compile,whats reason for this behaviour?
#include <stdio.h>
#include <stdlib.h>
int main()
{
void fun1(int);
void fun2(int);
int fun3(int);
int num = 5;
fun1(num);
fun2(num);
}
void fun1(int no)
{
no++;
fun3(no);
}
void fun2(int no)
{
no--;
fun3(no);
}
int fun3(int n)
{
printf("%d",n);
}
there is fail in compilation when declaration of fun3() is changed.
#include <stdio.h>
#include <stdlib.h>
int main()
{
void fun1(int);
void fun2(int);
void fun3(int); //fun3 return type changed to void error in compilation
int num = 5;
fun1(num);
fun2(num);
}
void fun1(int no)
{
no++;
fun3(no);
}
void fun2(int no)
{
no--;
fun3(no);
}
void fun3(int n) //fun3 return type changed to void error in compilation
{
printf("%d",n);
}
Prior to the C99 standard, if the compiler saw a function call without a function declaration in the same scope, it assumed that the function returned int
.
Neither fun1
nor fun2
declare fun3
before they call it, nor do they see the declaration in main
; the declaration of fun3
in main
is limited to the body of main
. Under C89 and earlier, the compiler will assume that the call to fun3
returns an int
. In the first example, the definition of fun3
returns an int
so the code will compile under a C89 compiler. In the second example, the definition of fun3
returns void
, which doesn't match the assumed int
type, so the code fails to compile.
Under C99 and later standards, neither snippet will compile; the compiler no longer assumes an implicit int
declaration for a function call. All functions must be explicitly declared or defined before they are called.