Does C have a “foreach” loop construct?

前端 未结 12 2219
情书的邮戳
情书的邮戳 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条回答
  •  Happy的楠姐
    2020-12-02 04:41

    Here is what I use when I'm stuck with C. You can't use the same item name twice in the same scope, but that's not really an issue since not all of us get to use nice new compilers :(

    #define FOREACH(type, item, array, size) \
        size_t X(keep), X(i); \
        type item; \
        for (X(keep) = 1, X(i) = 0 ; X(i) < (size); X(keep) = !X(keep), X(i)++) \
            for (item = (array)[X(i)]; X(keep); X(keep) = 0)
    
    #define _foreach(item, array) FOREACH(__typeof__(array[0]), item, array, length(array))
    #define foreach(item_in_array) _foreach(item_in_array)
    
    #define in ,
    #define length(array) (sizeof(array) / sizeof((array)[0]))
    #define CAT(a, b) CAT_HELPER(a, b) /* Concatenate two symbols for macros! */
    #define CAT_HELPER(a, b) a ## b
    #define X(name) CAT(__##name, __LINE__) /* unique variable */
    

    Usage:

    int ints[] = {1, 2, 0, 3, 4};
    foreach (i in ints) printf("%i", i);
    /* can't use the same name in this scope anymore! */
    foreach (x in ints) printf("%i", x);
    

    EDIT: Here is an alternative for FOREACH using the c99 syntax to avoid namespace pollution:

    #define FOREACH(type, item, array, size) \
        for (size_t X(keep) = 1, X(i) = 0; X(i) < (size); X(keep) = 1, X(i)++) \
        for (type item = (array)[X(i)]; X(keep); X(keep) = 0)
    

提交回复
热议问题