Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to put a function as an argument in C?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  1. Absolutly No C++ allowed.

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading