0

Consider,

    #include<stdio.h>
    int main()
    {
    int y = facto(6);
    printf("%d",y);
    return 0;
    }

    int facto(int x)
    {
    if(x==1)
      return 1;
    else 
      return x*facto(x-1);
    }

I read in some posts which said that calling a function before it is defined is an implicit declaration. How is this statement overhere ("y = facto(6)"), an implicit declaration ?

Using GCC 4.8.1 on Ubuntu 64 bit.

Blue Ice
  • 7,888
  • 6
  • 32
  • 52
kesari
  • 536
  • 1
  • 6
  • 16

2 Answers2

3

y=facto(6) is an implicit declaration because you're telling the compiler "I want to call a function and pass a single int, so somewhere down the road there will be a function with a single int parameter."

If the compiler ran into the int facto(int x) first, then that's the explicit declaration.

Implicit declarations are dangerous because the compiler won't say "Hey, this doesn't match what I've already found for the function."

Andy Lester
  • 91,102
  • 13
  • 100
  • 152
  • But it doesn't look like "int func();" right ? how are we "declaring" the function's presence ? – kesari Apr 06 '14 at 18:04
  • You're declaring the presence of the function by saying you want to call it. – Andy Lester Apr 06 '14 at 18:06
  • 1
    @Vinay: It compiles just fine under GCC. If you have `-Wall` on, you'll get a `./foo.c:4: warning: implicit declaration of function ‘facto’` warning, but it will still compile. – Andy Lester Apr 06 '14 at 18:11
2

Declaring, is saying the compiler there is function, facto in your case, defined somewhere. You don't say how many and which type parameters this function will have, and in your case even not saying which return type it have. It only works by accident, as you used int which is default return type. If you would have your function defined as something like this

  char facto(int x){...}

you would get an error. So don't use functions this way, either use prototypes, either define functions before you use them. Here some useful links :

1 2

Community
  • 1
  • 1
Dabo
  • 2,371
  • 2
  • 18
  • 26