Does C support function expressions function?

Is it possible to use function expressions in C? For example, I have the following code fragment (inside the main function):

 void print_line(char *data) { printf("%s\n", data); } // print all elements in my_list list_foreach(&my_list, print_line); 

I would like to do something like this:

 list_foreach(&my_list, void (char *data) { printf("%s\n", data); }); 

Is this possible in C?

+7
source share
4 answers

In a word, no. At least not in syntax like Javascript. Function pointers are as close as possible. There is little syntactic difference between them. If you are looking for behavior of closures or internal functions, then you definitely will not see them anytime soon.

+7
source

Not in C standard, no. Apple introduced a feature called blocks that will allow you to do this, and it was sent to standardize, but it does not exist yet (if it ever passes). Apple's syntax is as follows:

 list_foreach(my_list, ^(char *data) { printf("%s\n", data); }); 

It mainly uses pointer syntax with replacing * with ^ (and output for return type in expressions).

+4
source

You cannot do this in regular C. However, you can fake it with a macro:

 #define FOR_EACH(type, x, array, size, code) \ do { \ int i; \ for (i=0; i<size; ++i) { \ type x = array[i]; \ code \ } \ } while(0) int main() { int arr[] = {0,1,2,3,4,5,6}; FOR_EACH(int, x, arr, 7, printf("%d ", 1 << x); ); return 0; } 

EDIT
I coded the example to be more portable - without using the GCC block extension.

+2
source

Definitely not something like Objective-C blocks, closures, etc. But how to use function pointers ?

+1
source

All Articles