[英]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.