4

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

L_J
  • 2,351
  • 10
  • 23
  • 28
  • 3
    No you can't. A `#define` is processed even before compilation. But you could perhaps get the utility you're after using an associative array. – lurker May 31 '18 at 11:04
  • preprocessor directives are evaluated even before your compiler gets to see your code. – 463035818_is_not_an_ai May 31 '18 at 11:04
  • The second example expands to `cout << ik << endl`. It doesn't expand to `i0` if `k` has a value of `0`. In any event, rather than using macros, consider using an array (or in C++, one of the containers from the standard library) and access elements by index. – Peter May 31 '18 at 11:14

2 Answers2

7

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

Dan M.
  • 3,818
  • 1
  • 23
  • 41
0

The preprocessor does its job before the compiler. So #define can be used as a macro before compilation. However, it is not possible to evaluate at run-time in this way in C++.

You can instead use STL container such as std::vector or std::array

For example:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
    std::vector<int> vec {11,22,33,44,55,66};

    int k;
    cin >> k;                           // suppose user input '5'
    if (k > 0 && k < 6)
        cout << vec[k] << endl; 

    return 0;
}
Paul Belanger
  • 2,354
  • 14
  • 23
Nir
  • 1,608
  • 1
  • 17
  • 29