繁体   English   中英

你能在C中传递一个代码块给function吗?

[英]Can you pass a code block to a function in C?

我在 Linux kernel 上观看了一个视频,该视频可能会迁移到 C99 或 C11,该视频正在查看他们为什么要这样做的示例。

我一直看到 function 被这样调用:

list_for_each_entry(pos, &head, member) {
  /* this code gets run for each entry? */
}

我以前从未在 C 或 C++ 中见过这样的事情。但是,作为 Ruby 程序员,这对我来说很有意义,因为我习惯于做这样的事情:

arr.each do |item|
  # do something with the item
end

arr.each { |item| single_line_of_code_here }

从来不知道C有这个本事? 我试图了解更多相关信息,我猜这不是 function,而是宏? 有人可以向我解释这里发生了什么吗?

编辑:此处 function 的文档: https://www.kernel.org/doc/htmldocs/kernel-api/API-list-for-each-entry.html

显然,这是一个宏。 这个宏的源代码是:

/**
 * 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))

源代码(也包含其他迭代器): https://elixir.bootlin.com/linux/v5.16.1/source/include/linux/list.h#L629

在不使用预处理器宏的情况下,您可以使用 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM