Incrementing variables

This is a discussion on Incrementing variables within the C++ Programming forums, part of the General Programming Boards category; I have 4 variables called check1, check2, check3 & check4. I wish to apply the same code to all of ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    9

    Incrementing variables

    I have 4 variables called check1, check2, check3 & check4.
    I wish to apply the same code to all of them in turn.
    Is there any way I can do this in a loop by incrementing the number of the variable name (i.e. checkx) or do I really need to have the same code for each variable (i.e. the same code 4 times)?

  2. #2
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    as they stand now ..... NO

    if you define an array called check with 4 elements you could use a loop and assign in the loop like this....

    check[i]=0; // where i is your loop variable.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  3. #3
    Visitor
    Guest
    depending on your compiler, you can make use of the precompiler directives to accomplish what you want.

    use the number define as follows:

    #define adder( x, y ) ( check##x += y )

    And in your code:

    adder( 1, 4 ); // adds 4 to check1
    adder( 3, 2 ); // adds 2 to check3

  4. #4
    Skunkmeister Stoned_Coder's Avatar
    Join Date
    Aug 2001
    Posts
    2,572
    well pointed out. I forgot about token pasting, a feature of c/c++ that I haven't used for years. But I would still prefer the array way.
    Free the weed!! Class B to class C is not good enough!!
    And the FAQ is here :- http://faq.cprogramming.com/cgi-bin/smartfaq.cgi

  5. #5
    Unregistered Leeman_s's Avatar
    Join Date
    Oct 2001
    Posts
    753

    yes

    Use arrays

    for(x;x<5;x++)
    {
    check[x]=whatever
    {

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. basic question about global variables
    By radeberger in forum C++ Programming
    Replies: 0
    Last Post: 04-06-2009, 01:54 AM
  2. Replies: 15
    Last Post: 09-30-2008, 03:12 AM
  3. esbo's data sharing example
    By esbo in forum C Programming
    Replies: 49
    Last Post: 01-08-2008, 11:07 PM
  4. Global Variables
    By Taka in forum C Programming
    Replies: 34
    Last Post: 11-02-2007, 04:25 AM
  5. Replies: 6
    Last Post: 01-02-2004, 01:01 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21