Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C, function pointer with arguments preset

Is something like this possible in C?

#include <stdio.h>

void print_str(char *str) {
        printf(str);
}

int main() {

        void (*f_ptr)() = print_str,"hello world";

        f_ptr();

}

//see "hello world" on stdout

In short, I'd like to have a function pointer that "stores" the arguments. The point is that the function pointer can be used later on without needing a reference to the original data.

I could use something like this to couple a function pointer and an argument reference

struct f_ptr {
 void (*f)();
 void *data;
}

void exec_f_ptr(f_ptr *data) {
  data->f(data->data):
}

but wouldn't be as elegant as just calling a function pointer with the argument inside.

like image 676
Mike Avatar asked Jun 30 '10 04:06

Mike


People also ask

How do you pass a function pointer as an argument?

Pass-by-pointer means to pass a pointer argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the variable to which the pointer argument points. When you use pass-by-pointer, a copy of the pointer is passed to the function.

CAN default arguments be provided for pointers to functions?

Default argument cannot be provided for pointers to functions.

Can C functions have default arguments?

C has no default parameters.

Can we use pointer with function in C?

In C, like normal data pointers (int *, char *, etc), we can have pointers to functions. Following is a simple example that shows declaration and function call using function pointer.


3 Answers

What you want is a closure or a curried function. Unfortunately, C has neither of these. (Apple did introduce closures in its version of C and hopefully they'll be adopted for some future version of the language, but it's not part of C99.)

like image 122
Chuck Avatar answered Sep 30 '22 03:09

Chuck


You're basically asking for a closure rather than a function pointer--that is, data and code in one "object." Such objects don't exist in standard C--you can get something similar from Apple's blocks or from anonymous functions in other languages (or from closures outright in the languages that support them) but generally speaking you'll have to construct some data type of your own, as you've discovered.

like image 24
Jonathan Grynspan Avatar answered Sep 30 '22 03:09

Jonathan Grynspan


GLib has support for closures, used mainly for signal callbacks. It's cross platform, and might be worth a look (depending on your requirements). (See also the GLib closure API.)

like image 34
detly Avatar answered Sep 30 '22 04:09

detly