简体   繁体   中英

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();
}

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM