简体   繁体   中英

Can we define a function into another function?

int main()
{

  static int fun(){}
  return 0;
}

** If we define a function into another then why this code is giving following error:**

Error: invalid storage class for function 'fun'

This is called "nested function". It's not supported in C. Some compilers, such as gcc , offer it as language extension. You do not need the static keyword though.

C does not support nested functions, simple as that.

To answer the question in comment about gcc non-standard nested functions and static keyword: as explained in the gcc manual (link credit to the other answer ):

A nested function always has no linkage. Declaring one with extern or static is erroneous.

In other words, static keyword does not work, because it is explicitly documented to be invalid syntax, because it can not mean what people would expect it to mean.


For comparison, standard C++ has the workaround of being able to define class/struct member functions along with the class/struct also inside a function. And C++11 has proper lambda syntax too. But no such things in standard C.

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