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++?
No, it's not possible. However, you could place those variables/values into an array (or map) and access them by index.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With