Home > Software design >  How to put a function as an argument in C?
How to put a function as an argument in C?

Time:06-11

I would like to execute a function given in the paramater of a function. Let me explain with an example.

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int object() {
    printf("Hello, World!");
    return 0;
}

int run_func( int a_lambda_function() ) {
    a_lambda_function();
    return 0;
}

int main() {
    run_func( object() );
    return 0;
}

Now, I want to run "object()" in the parameters of "run_func(int a_lambda_function()"). When I run it, It returns an error. How would I achieve this is full C?

Restrictions I have:

  1. Absolutly No C allowed.

CodePudding user response:

Functions can be passed as arguments or stored into variables as function pointers.

The definition for a function pointer compatible with your object function is int (*funcp)() ie: a pointer to a function taking an unspecified number of arguments and returning int.

In modern C, functions with an unspecified number of arguments are not used anymore, and functions taking no arguments must be declared with a (void) argument list.

Here is a modified version:

#include <stdio.h>

int object(void) {
    printf("Hello, World!");
    return 0;
}

int run_func(int (*a_lambda_function)(void)) {
    return a_lambda_function();  // can also write (*a_lambda_function)()
}

int main() {
    return run_func(object);
}
  • Related