這裏是我的代碼,我發現「each」宏只迭代第一個元素並輸出「s1」,如何讓它迭代所有元素?c「each」macro does not iterate all elements
#include "stdio.h"
#define each(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)
char *join(char const *ss[]) {
char *r = "";
each(char *s, ss) {
puts(s);
}
return (r);
}
int main(int argc, char **argv) {
char const *ss[] = {"s1", "s2"};
join(ss);
};
請不要寫這樣的宏;不要試圖改變C語言。你可以假設每個其他的C程序員都知道C.你不能假設他們知道或關心瞭解你的家庭釀造的祕密宏語言。這是非常糟糕的編程習慣。 – Lundin
在一個名爲'each'的宏中放置一個雙嵌套循環並不是一個好主意。這個邏輯比你可以考慮的「樣板」更復雜。另外,當你做的功能不像函數時,你應該使用大寫宏名稱。 (例如,如果使用GNU C特性來避免多次評估它的參數,那麼'max'宏可能沒問題。) –