Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the issue with this C function that contains a function?

Tags:

c

recursion

My professor showed us this code:

timerX(int x){

     int times(int y){
          return x * y;
     }
     return times;

}

How does this work in C(using GCC compiler)? He said that as soon as the function disappears the inside function disappears? I appreciate any tips or advice.

like image 907
Caffeinated Avatar asked Mar 12 '12 19:03

Caffeinated


People also ask

What happens when a function is called in C?

Function Calling: A function call is an important part of the C programming language. It is called inside a program whenever it is required to call a function. It is only called by its name in the main() function of a program. We can pass the parameters to a function calling in the main() function.

What is error function C?

In C/C++, the library function ferror() is used to check for the error in the stream. Its prototype is written as: int ferror (FILE *stream); The ferror() function checks for any error in the stream. It returns a value zero if no error has occurred and a non-zero value if there is an error.

What is the argument of a function in C?

What is Argument? The values that are declared within a function when the function is called are known as an argument. These values are considered as the root of the function that needs the arguments while execution, and it is also known as Actual arguments or Actual Parameters.

How do you fix undefined reference to function in C?

The error: undefined reference to function show() has appeared on the terminal shell as predicted. To solve this error, simply open the file and make the name of a function the same in its function definition and function call.


1 Answers

It's called a nested function, a GNU extension. Basically

  • the inner function can acess the local variables of the outer function (the ones declared prior to its apparition)

  • the inner function can only be called from outside via function poinyers but not after the containing function has terminated if the inner function accesses objects from its parent

In your example, calling that function pointer from outside will probably be illegal.

If you try to call the nested function through its address after the containing function has exited, all hell will break loose.

like image 77
cnicutar Avatar answered Sep 25 '22 09:09

cnicutar