Does C have a “foreach” loop construct?

前端 未结 12 2264
情书的邮戳
情书的邮戳 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:18

    Here's a simple one, single for loop:

    #define FOREACH(type, array, size) do { \
            type it = array[0]; \
            for(int i = 0; i < size; i++, it = array[i])
    #define ENDFOR  } while(0);
    
    int array[] = { 1, 2, 3, 4, 5 };
    
    FOREACH(int, array, 5)
    {
        printf("element: %d. index: %d\n", it, i);
    }
    ENDFOR
    

    Gives you access to the index should you want it (i) and the current item we're iterating over (it). Note you might have naming issues when nesting loops, you can make the item and index names be parameters to the macro.

    Edit: Here's a modified version of the accepted answer foreach. Lets you specify the start index, the size so that it works on decayed arrays (pointers), no need for int* and changed count != size to i < size just in case the user accidentally modifies 'i' to be bigger than size and get stuck in an infinite loop.

    #define FOREACH(item, array, start, size)\
        for(int i = start, keep = 1;\
            keep && i < size;\
            keep = !keep, i++)\
        for (item = array[i]; keep; keep = !keep)
    
    int array[] = { 1, 2, 3, 4, 5 };
    FOREACH(int x, array, 2, 5)
        printf("index: %d. element: %d\n", i, x);
    

    Output:

    index: 2. element: 3
    index: 3. element: 4
    index: 4. element: 5
    

提交回复
热议问题