C 有“foreach"吗?循环构造? [英] Does C have a "foreach" loop construct?
本文介绍了C 有“foreach"吗?循环构造?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
几乎所有语言都有 foreach
循环 或类似的东西.C有吗?你能发布一些示例代码吗?
Almost all languages have a foreach
loop or something similar. Does C have one? Can you post some example code?
推荐答案
C 没有 foreach,但经常使用宏来模拟:
C doesn't have a foreach, but macros are frequently used to emulate that:
#define for_each_item(item, list)
for(T * item = list->head; item != NULL; item = item->next)
并且可以像这样使用
for_each_item(i, processes) {
i->wakeup();
}
也可以对数组进行迭代:
Iteration over an array is also possible:
#define foreach(item, array)
for(int keep = 1,
count = 0,
size = sizeof (array) / sizeof *(array);
keep && count != size;
keep = !keep, count++)
for(item = (array) + count; keep; keep = !keep)
并且可以像这样使用
int values[] = { 1, 2, 3 };
foreach(int *v, values) {
printf("value: %d
", *v);
}
如果您也对 C++ 解决方案感兴趣,C++ 有一个原生的 for-each 语法,称为基于范围的 for"
In case you are also interested in C++ solutions, C++ has a native for-each syntax called "range based for"
这篇关于C 有“foreach"吗?循环构造?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文