Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to build variable name at runtime in C++? [duplicate]

I have variables named in an ordered manner, i1, i2, i3, ... I am trying to access those variables at runtime using the numeric part of the variables names.

Here are codes I try to use for this problem. It does not work properly.

#include <iostream>
using namespace std;

#define CreateVariable(c,v) c##v

int main()
{
    int i1(11), i2(22), i3(33), i4(44), i5(55);
    cout << CreateVariable(i, 3) << endl;   // This is working and prints "33"

    int k;
    cin >> k;                           // suppose user input '5'
    if (k > 0 && k < 6)
        cout << CreateVariable(i, k) << endl;  // This is not working

    return 0;
}

Is it possible to achieve that in C++?

like image 809
L_J Avatar asked Mar 06 '23 02:03

L_J


1 Answers

No, it's not possible. However, you could place those variables/values into an array (or map) and access them by index.

like image 169
Dan M. Avatar answered Apr 27 '23 01:04

Dan M.