Vindhya G
Vindhya G

Reputation: 1369

function declaration inside main and also outside main in C

The first program compiled properly.second gave error saying too few argument for foo... is global declaration ignored by the compiler in both programs?

first program:

#include<stdio.h>
    void foo();
int main()
{
  void foo(int);
  foo(1);
  return 0;
}

void foo(int i)
{
   printf("2 ");
}

void f()
{
   foo(1);
}

second program:

void foo();
int main()
{
  void foo(int);
  foo();
  return 0;
}

void foo()
{
   printf("2 ");
}

void f()
{
   foo();
}

Upvotes: 5

Views: 13437

Answers (2)

eyalm
eyalm

Reputation: 3366

I see that you investigate the specific behavior of inner declaration but why not:

#include<stdio.h>

void foo(int);

int main()
{
    foo(1);
    return 0;
}

void foo(int i)
{
   printf("2 ");
}

void f()
{
   foo(1);
}

or even:

#include<stdio.h>

void foo(int i)
{
   printf("2 ");
}

void f()
{
   foo(1);
}

int main()
{
    foo(1);
    return 0;
}

Upvotes: 0

K-ballo
K-ballo

Reputation: 81349

The inner declaration hides declarations at the global scope. The second program fails because the declaration void foo(int); hides the global declaration void foo();; so when you say foo within main you are referring to the one taking an int as argument.

Upvotes: 7

Related Questions