2

Possible Duplicate:
Nested function in C

In C, if i wrote a program in this structure:

main ()
{
  int function1(...)
  {
    ....
  }
}

function 2()
{
   function1(...)
}

It is possible to call function1 from function2 that was written inside the main function? and also: In C all the functions are global? or there is some restriction in some situation that from one function you cant call another one?

Community
  • 1
  • 1
Yuval
  • 1,721
  • 4
  • 16
  • 15

2 Answers2

3

You cannot nest function definitions in C.

int main(void)
{
  int function1(void)
  {
      /* ... */
  }
}

The definition of function1 above is not valid.

ouah
  • 142,963
  • 15
  • 272
  • 331
  • Euhm. When I try, I can. gcc 4.6.3 – Bart Friederichs Jan 09 '13 at 13:28
  • 1
    @BartFriederichs this is valid in GNU C, see http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html but not in C. – ouah Jan 09 '13 at 13:30
  • 1
    @BartFriederichs Who cares about the non-standard GNU-goo language? Compile with a C compiler. Conveniently, GCC also supports the C language: `-std=c99 -pedantic-errors`. – Lundin Jan 09 '13 at 13:34
0

EDIT

In GNU C is possible to nest functions. I tried this little snippet and it worked

#include <stdio.h>

int main()
{
    void printy() { printf("hallo\n"); }

    printy();
}

like GNU C page claims http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html

The nested function's name is local to the block where it is defined

Infact, if i change my code to

#include <stdio.h>

void func2();

int main()
{
    void printy() { printf("hallo\n"); }

    printy();

    func2();
}

void func2()
{
    printy();
}

i get

gcc test.c
/tmp/ccGhju4n.o: In function `func2':
test.c:(.text+0x3f): undefined reference to `printy'
collect2: ld returned 1 exit status
Davide Berra
  • 6,387
  • 2
  • 29
  • 50
  • This is too vague, you can declare a function inside another function but you can't define it. However, the downvote isn't mine. – effeffe Jan 09 '13 at 13:30
  • you're right and i was wrong... i edited my post... it's incredible how many thing i don't know but i was sure i knew them – Davide Berra Jan 09 '13 at 13:37
  • @DavideBerra That's because you're calling `printy` outside the scope in which it was defined (which is `main`). The answers that say you can't do this in C are correct, but if gcc allows it as an extension you still have to expect normal rules of scope to apply. – Caleb Jan 09 '13 at 13:58