Estaba viendo un video sobre el cambio del kernel de Linux a C99 o C11 posiblemente y el video mostraba un ejemplo de por qué van a hacer esto.
Seguí viendo una función que se llama así:
list_for_each_entry(pos, &head, member) { /* this code gets run for each entry? */ }Nunca antes había visto algo así en C o C++. Sin embargo, como programador de Ruby, esto tiene sentido para mí porque estoy acostumbrado a hacer algo como esto:
arr.each do |item| # do something with the item end arr.each { |item| single_line_of_code_here }¿Nunca supe que C tenía esta habilidad? Estaba tratando de aprender más sobre esto y supongo que esto no es una función, sino tal vez una macro. ¿Alguien puede explicarme qué está pasando aquí?
Editar: Documentación para esta función aquí: https://www.kernel.org/doc/htmldocs/kernel-api/API-list-for-each-entry.html
Aparentemente, esto ES una macro. El código fuente de esta macro es:
/** * 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))El código fuente (que también contiene otros iteradores): https://elixir.bootlin.com/linux/v5.16.1/source/include/linux/list.h#L629
Sin usar macros de preprocesador, puede lograr algo similar con punteros de función.
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; }