Thread: Can you use a variable in the name of a variable?

  1. #1
    Registered User
    Join Date
    Nov 2018

    Can you use a variable in the name of a variable?

    In this code I'm working on

    function(int n) {
    block[3].whole = cashless1.displayData[1];
    block[4].whole = cashless1.displayData[2];
    block[5].whole = cashless1.displayData[3];
    block[6].whole = cashless1.displayData[4];
    block[7].whole = cashless1.displayData[5];
    block[8].whole = cashless1.displayData[6];
    block[9].whole = cashless1.displayData[7];
    block[2].whole = cashless1.displayData[0];
    I have two identical cashless payment devices with the only difference between them in the code being the number in their name/tag.
    I have functions that are set up to interact with one cashless payment device at a time, and I'm trying to add the functionality of being able to switch betwween which device the functions interact with, by giving it a number when you call the function.

    Is there a way to edit all the references/tags for the 'cashless1' device, and have something like 'cashless#' where the pound sign is a variable/number that inserts the value given to 'n' when you call the function? Basically is there a way you can insert 'n' into the cashless device variables so I don't have to make a new copy of each function for each device that exists?

  2. #2
    Registered User
    Join Date
    Dec 2017
    No, there is no such thing as a "variable" variable name.

    If I understand your situation, the best way to do it is to make the "cashless" variable a parameter to your function:
    typedef struct Cashless {
        int x, y;
    } Cashless;
    void function(Cashless *cashless) {
        cashless->x = 24;
        cashless->y = 42;
    int main() {
        Cashless cashless1, cashless2;  // or use an array
        return 0;
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 05-04-2017, 11:07 PM
  2. Replies: 5
    Last Post: 10-25-2014, 10:36 PM
  3. Replies: 7
    Last Post: 04-16-2011, 12:28 PM
  4. Replies: 8
    Last Post: 02-14-2010, 04:14 PM
  5. Variable Names based on Variable Values
    By mrpickle in forum C++ Programming
    Replies: 6
    Last Post: 01-27-2003, 10:33 AM

Tags for this Thread