[英]Can you pass a code block to a function in C?
I was watching a video on the Linux kernel moving to C99 or C11 possibly and the video was looking at an example for why they are going to do this.我在 Linux kernel 上观看了一个视频,该视频可能会迁移到 C99 或 C11,该视频正在查看他们为什么要这样做的示例。
I kept seeing a function being called like this:我一直看到 function 被这样调用:
list_for_each_entry(pos, &head, member) {
/* this code gets run for each entry? */
}
I've never seen something like this before in C or C++. However, as a Ruby programmer this makes sense to me because I'm used to doing something like this:我以前从未在 C 或 C++ 中见过这样的事情。但是,作为 Ruby 程序员,这对我来说很有意义,因为我习惯于做这样的事情:
arr.each do |item|
# do something with the item
end
arr.each { |item| single_line_of_code_here }
I never knew that C had this ability?从来不知道C有这个本事? I was trying to learn more about this and my guess is this isn't a function but maybe a macro?
我试图了解更多相关信息,我猜这不是 function,而是宏? Can someone explain to me what's happening here?
有人可以向我解释这里发生了什么吗?
Edit: Documentation for this function here: https://www.kernel.org/doc/htmldocs/kernel-api/API-list-for-each-entry.html编辑:此处 function 的文档: https://www.kernel.org/doc/htmldocs/kernel-api/API-list-for-each-entry.html
Apparently, this IS a macro.显然,这是一个宏。 The soure code for this macro is:
这个宏的源代码是:
/**
* list_for_each_entry - iterate over list of given type
* @pos: the type * to use as a loop cursor.
* @head: the head for your list.
* @member: the name of the list_head within the struct.
*/
#define list_for_each_entry(pos, head, member) \
for (pos = list_first_entry(head, typeof(*pos), member); \
!list_entry_is_head(pos, head, member); \
pos = list_next_entry(pos, member))
The source code (which contains other iterators as well): https://elixir.bootlin.com/linux/v5.16.1/source/include/linux/list.h#L629源代码(也包含其他迭代器): https://elixir.bootlin.com/linux/v5.16.1/source/include/linux/list.h#L629
Without using preprocessor macros you can accomplish something akin to this with function pointers.在不使用预处理器宏的情况下,您可以使用 function 指针完成类似的操作。
typedef void (*fp_t)(int);
void int_array_iter(int *arr, size_t n, fp_t f) {
for (size_t i = 0; i < n; i++) {
f(arr[i]);
}
}
void print_int(int i) {
printf("%d\n", i);
}
int main(void) {
int arr[] = { 1, 2, 3, 4, 5, 6 };
int_array_iter(arr, 6, print_int);
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.