Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a function inside the input of another function in C

I have a function which has a function pointer input. I can easily give function names to it as input. But I wonder if it's possible to define a function as input. For example I have a function like this;

void exampleFunction ( void (*functionPointer)( void ) ) {
  codes
  ...
}

Can I give an input like this inside the brackets? For example;

exampleFunction( void helloFunction ( void ) {
  printf("Hello");
} );

It gives compilation error like this but is there any other ways to do it?

like image 613
Ali Devrim Oğuz Avatar asked Jun 06 '15 14:06

Ali Devrim Oğuz


People also ask

Can we define function inside another function in C?

Nested function is not supported by C because we cannot define a function within another function in C.

Can a function be defined inside another function?

Explanation: A function cannot be defined inside the another function, but a function can be called inside a another function.

What is nested function in C?

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 we pass a function to another function in C?

We cannot pass the function as an argument to another function. But we can pass the reference of a function as a parameter by using a function pointer. This process is known as call by reference as the function parameter is passed as a pointer that holds the address of arguments.


1 Answers

This is impossible in C.

In C++, you can use a lambda-expression:

exampleFunction([](){ std::cout << "Hello"; });
like image 133
molbdnilo Avatar answered Nov 15 '22 04:11

molbdnilo