Does C have a “foreach” loop construct?

前端 未结 12 2211
情书的邮戳
情书的邮戳 2020-12-02 03:49

Almost all languages have a foreach loop or something similar. Does C have one? Can you post some example code?

12条回答
  •  春和景丽
    2020-12-02 04:41

    If you're planning to work with function pointers

    #define lambda(return_type, function_body)\
        ({ return_type __fn__ function_body __fn__; })
    
    #define array_len(arr) (sizeof(arr)/sizeof(arr[0]))
    
    #define foreachnf(type, item, arr, arr_length, func) {\
        void (*action)(type item) = func;\
        for (int i = 0; i

    Usage:

    int ints[] = { 1, 2, 3, 4, 5 };
    foreach(int, i, ints, {
        printf("%d\n", i);
    });
    
    char* strs[] = { "hi!", "hello!!", "hello world", "just", "testing" };
    foreach(char*, s, strs, {
        printf("%s\n", s);
    });
    
    char** strsp = malloc(sizeof(char*)*2);
    strsp[0] = "abcd";
    strsp[1] = "efgh";
    foreachn(char*, s, strsp, 2, {
        printf("%s\n", s);
    });
    
    void (*myfun)(int i) = somefunc;
    foreachf(int, i, ints, myfun);
    

    But I think this will work only on gcc (not sure).

提交回复
热议问题