Concatenating Variable Names in C?

When you find yourself adding an integer suffix to variable names, think I should have used an array.

struct mystruct {
    int class[6];
};

int main(void) {
    struct mystruct s;
    int i;
    for (i = 0; i < 6; ++i) {
        s.class[i] = 1000 + i;
    }

    return 0;
}

Note: A C++ compiler will barf at this because of class. You will need to figure out a different name for that field if you plan to compile this code as C++.

Leave a Comment