Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function inside function in C

Anybody please elaborate these error:-

void main()
{
    int a=5, b=60, func();

    printf("\nI am in main-1");

    int func(){
        printf("\nI am in funct");
        return 1;
    }
    func();
    printf("\nI am in main-2");
}

The errors I get are:

  • In function 'main':
  • Line 8: error: static declaration of 'func' follows non-static declaration
  • Line 4: error: previous declaration of 'func' was here
  • Line 3: warning: return type of 'main' is not 'int'

I think C allows nested class because the following code is working fine:

void outerfunc()
{
    int func()
    {
        printf("\nI am in funct");
        return 1;
    }

    func();
}

void main()
{
    printf("\nI am in main-1");

    outerfunc();
    printf("\nI am in main-2");
}
like image 749
Kuntal Basu Avatar asked Sep 06 '11 11:09

Kuntal Basu


People also ask

Can I define a function inside a function?

If you define a function inside another function, then you're creating an inner function, also known as a nested function. In Python, inner functions have direct access to the variables and names that you define in the enclosing function.

Are nested functions allowed in C?

C does not enable nested functions because we cannot define a function within another function in C. It is possible to declare a function within a function, but this is not a nested function.

What is nested function in C with example?

A nested function is a function defined inside the definition of another function. It can be defined wherever a variable declaration is permitted, which allows nested functions within nested functions. Within the containing function, the nested function can be declared prior to being defined by using the auto keyword.

Can you declare a function within a function in C++?

No, it's not allowed. Neither C nor C++ support this feature by default, however TonyK points out (in the comments) that there are extensions to the GNU C compiler that enable this behavior in C.


2 Answers

You are using an extension of the GNU C Compiler which allows the declarations of nested functions. The error comes from the fact, that forward declarations of nested functions under GCC's extension need to be prepended with the auto keyword.

int a=20,b=11;
int main()
{
  int a=5, b=60; 
  auto int func(); // <--------- here
  func(); // <- call it
  printf("\nI am in main-1");

  int func(){
  printf("\nI am in funct");
  return 1;
  }

printf("\nI am in main-2");
 return 0;
}

See http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html for more details.

like image 56
Nordic Mainframe Avatar answered Oct 12 '22 05:10

Nordic Mainframe


ANSI C doesn't allow nested function definition. And your main function should return int.

like image 34
Mu Qiao Avatar answered Oct 12 '22 05:10

Mu Qiao