Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 936
thejh Avatar asked Apr 13 '12 18:04

thejh


People also ask

Is a function call an expression?

A function call is an expression that includes the name of the function being called or the value of a function pointer and, optionally, the arguments being passed to the function.

What are expressions in C++?

Expression is the combination of the constants, variables, and operators, which are arranged according to the syntax of C++ language and, after computation, return some values that may be a boolean, an integer, or any other data type of C++.

What are built in functions in C?

Built-in functions are ones for which the compiler generates inline code at compile time. Every call to a built-in function eliminates a runtime call to the function having the same name in the dynamic library.

Why are functions called as part of an expression?

If the function is created as a part of an expression, it's called a “Function Expression”. Function Declarations are processed before the code block is executed. They are visible everywhere in the block. Function Expressions are created when the execution flow reaches them.


2 Answers

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.

like image 53
D.Shawley Avatar answered Oct 21 '22 12:10

D.Shawley


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).

like image 39
Chuck Avatar answered Oct 21 '22 13:10

Chuck