Thread: Variables in variable names

  1. #1
    Registered User
    Join Date
    Jan 2017
    Posts
    7

    Variables in variable names

    Hi,
    I am creating a code for a database for a uni project and I have run into a problem, and I have a subsequent question!
    When creating records to go in the database (string format) I would like to name the variables data'number' , where 'number' is another variable which counts the number of records in the database. I know this is not possible because visual Studio throws up an error! So is there a way of doing something like this? I am relatively new to C and I don't know much so this would be a great help.
    Thank you!
    Brad

  2. #2
    Registered User
    Join Date
    Jun 2011
    Posts
    4,509
    You can use sprintf() to "print" variables to a string - as that what you're after?

    There's not really a way to create "dynamic" variable names in C, at least not ways that would be very useful for you.

    Code:
    $ cat cboard.c
    #define VAR(x, y) (x##y)
    
    int main(void)
    {
        int VAR(Test, 12) = 5;
        
        return 0;
    }
    $ gcc cboard.c -E
    << snip >>
    
    int main(void)
    {
        int (Test12) = 5;
    
        return 0;
    }

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    37,421
    > I would like to name the variables data'number' , where 'number' is another variable which counts the number of records in the database.
    How would this differ from an array like data[number]?

    You can create dynamic arrays just fine in C.
    Code:
    int number = 10; // you get this from wherever you want
    int *data = malloc( number * sizeof(*data) );
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. underscore and variable names
    By l2u in forum C++ Programming
    Replies: 2
    Last Post: 06-10-2007, 09:57 AM
  2. Generating data file names from program variables
    By a380x in forum C Programming
    Replies: 2
    Last Post: 12-18-2006, 12:12 PM
  3. i j k variable names
    By swgh in forum A Brief History of Cprogramming.com
    Replies: 13
    Last Post: 10-12-2006, 04:25 PM
  4. Variable Names based on Variable Values
    By mrpickle in forum C++ Programming
    Replies: 6
    Last Post: 01-27-2003, 10:33 AM
  5. variable names
    By trekker in forum C Programming
    Replies: 3
    Last Post: 03-16-2002, 03:37 AM

Tags for this Thread