if prototype of type int given, the program works but if void given the program doesnt

Here's the code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
 #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.
> int fun3(int); // this works fine
please read the warnings.
bar.c:31:6: warning: conflicting types for ‘fun3’ [enabled by default]
bar.c:9:6: note: previous implicit declaration of ‘fun3’ was here


I'm going to assume that your code is C, not C++
http://stackoverflow.com/questions/9182763/implicit-function-declarations-in-c


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.
Topic archived. No new replies allowed.