Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenating Variable Names in C?

Tags:

c

variables

names

Is it possible to concatenate variable names in C? Specifically, I have a struct that contains 6 similar variables in it called class1, class2, class3, etc.

I want to run through a for loop to assign each variable a value, but I can't see how to do it without somehow concatenating the variable name with the value of the for loop counter.

How else could I do this?

like image 503
Tyler Treat Avatar asked Dec 02 '09 00:12

Tyler Treat


3 Answers

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++.

like image 101
Sinan Ünür Avatar answered Sep 18 '22 02:09

Sinan Ünür


There are dynamic languages where you can do this sort of thing - C is not one of these languages. I agree with Sinan - arrays or STL vectors are the way to go.

As a thought experiment - what would happen if you have 100,000 of these variables? Would you have 100,000 lines of code to initialise them?

like image 27
Charlie Salts Avatar answered Sep 20 '22 02:09

Charlie Salts


The C preprocessor can concatenate symbols, but have you considered just using an array?

like image 20
amrox Avatar answered Sep 21 '22 02:09

amrox