Home > Back-end >  Is there any way to have as much variables in struct in c as I want? C
Is there any way to have as much variables in struct in c as I want? C

Time:12-25

For example, after starting the program, I specify the number 4, and there are only 4 variables in my struct - x1, x2, x3, x4. If I enter 2 the next time I start the program, I will only have x1, x2. Is that even possible?

CodePudding user response:

You can select the number of members of a struct at compile time and with template specialization you can even name them x1,x2,...

template <unsigned N>
struct foo;

template <>
struct foo<2> {
    int x1;
    int x2;
};

template <>
struct foo<4> {
    int x1;
    int x2;
    int x3;
    int x4;
};

Now foo<2> has members x1 and x2 and foo<4> has members x1,x2,x3 and x4. However, you can only choose between foo<2> and foo<4> at compile time. Moreover the above is a little silly. Nobody would actually write code like that.

At runtime you would have to resort to runtime polymorphism, but I also doubt that that is what the exercise is asking you to do.

Whenever you feel like naming variables x1,x2,x3, ... then you actually want an array or vector:

 struct bar {
      std::vector<int> data;
      bar(unsigned size) : data{size} {}
 };

Now bar b2{2}; holds 2 elements while bar b4{4}; holds 4 elements.

CodePudding user response:

You can't have this in C . The closest thing I can think of is using std::map. For example, here's a sample code to achieve this:

std::map<int, int> variables;
int numberOfVariables;
std::cin >> numberOfVariables;
for (int i = 1; i <= numberOfVariables; i  )
    variables[i] = SOME_VALUE;

With using maps, you can access your ith variable with variables[i].

I recommend reading about maps (and other containers of C ) to get a better idea of what you can and can't do. cppreference is a good source for this.

  •  Tags:  
  • c
  • Related