#include <stdio.h>
#include <stdlib.h>
int main()
{
void fun1(int);
void fun2(int);
int fun3(int); // this works fine but if prototype is changed to void fun3(int) it throws an error namely
// error: incompatible implicit declaration of function 'fun3'
//I've to shift the prototype outside main to make it work
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)
{
printf("%d",n);
}
I can't figure out why this happens, why an error when void but not when int. Also I would like to know when should the prototype be given outside main and when it's allowed to be given inside main.
Make sure you use the same return type when declaring the function as when you define it.
If you declare the fun3 inside main it will only be visible inside main so the compiler will give you an error when you try to call the fun3 inside fun1 and fun2.
Because you have declared the function inside main(), only main() knows about its existence.
When you try to use it in in fun1(), the function is implicit declared and void fun3(int) conflicts with int fun3()
Best avoid nested function declarations, i.e. declare all your functions outside other functions, before they are used.
What's happening here (I think) is as follows:
You declared the functions in main(), so the visibility of those declarations is limited to main. When you call the fn3() from fn1() or fn2(), the declaration in main is out of scope, so it is implicitly delared for you.
However, it implicitly declares it as returning an int, i.e. as "int fn3(int)". Unfortunately, this does not match the declaration in main() so there is a conflict.
In other words when you are in fun1() or fun2(), you are trying to call int fun3(int), but there's a conflicting void fun3(int)
The implicit declaration done by C is what's causing the confusion, if you compile this with a C++ compiler, you'll get compiler errors that will shed more light on the situation.