thejh
thejh

Reputation: 45578

Does C support function expressions?

Is it possible to use function expressions in C? For example, I have the following code snippet (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'd like to do something like this instead:

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

Is anything like that possible in C?

Upvotes: 7

Views: 278

Answers (4)

Agnius Vasiliauskas
Agnius Vasiliauskas

Reputation: 11277

You can't do that in plain C. However you can fake this with 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've re-coded example to be more portable - without using GCC blocks extension.

Upvotes: 2

Chuck
Chuck

Reputation: 237100

Not in standard C, no. Apple has introduced a feature called blocks that will let you do this and it's been submitted for standardization, but it's not there yet (if it will ever make it through). Apple's syntax looks like this:

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

It's basically function pointer syntax with * replaced with ^ (and inference for the return type in expressions).

Upvotes: 4

Dr.Kameleon
Dr.Kameleon

Reputation: 22820

Definitely not anything like Objective-C blocks, closures, etc. But what about using function pointers instead?

Upvotes: 1

D.Shawley
D.Shawley

Reputation: 59583

In a word, No. At least not in a Javascript-like syntax. Function pointers are as close as your are going to get. There is very little difference between the two syntactically. If you are looking for the behavior of closures or inner functions, then you definitely are not going to see them soon.

Upvotes: 7

Related Questions