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?
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.
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++.
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.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With