Thread: Declare variables inside loops the right way?

  1. #1
    Registered User
    Join Date
    Mar 2015
    Posts
    6

    Declare variables inside loops the right way?

    I am trying to declare variables inside a loop, I did some research but still don't know which is the best way to achieve it.
    My code so far:
    Code:
    for(unsignedint i =0; i<something.size(); i++){
            char name[2];
            itoa (i, name,10);
            boolDo+name = bool_function(somedata+name);//<- bool Do+name is the new variable
    }


  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    What is the bigger picture of what you're trying to do, or how does your current code not work?
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,662
    You can't create new named variables at runtime.

    When you're trying to create var1, var2, var3, it should be screaming at you - use an array!

    It seems to me that all you need is
    Code:
    bool *Do = new bool[something.size()];
    or
    Code:
    vector<bool> Do(something.size());
    Then inside the loop, you have
    Code:
    Do[i] = bool_function(somedata+name);
    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.

  4. #4
    Registered User
    Join Date
    Mar 2015
    Posts
    6
    Thanks @salem

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. How to declare these variables
    By jim_0 in forum C Programming
    Replies: 11
    Last Post: 02-14-2014, 02:32 AM
  2. Declare many Variables
    By Engineer1 in forum C Programming
    Replies: 16
    Last Post: 08-21-2013, 01:22 PM
  3. Where to declare variables - Best Practise
    By darren78 in forum C++ Programming
    Replies: 1
    Last Post: 09-27-2009, 03:18 AM
  4. declare function inside fork()
    By MK27 in forum C Programming
    Replies: 35
    Last Post: 02-03-2009, 06:56 PM
  5. declaring variables inside loops
    By samus250 in forum C Programming
    Replies: 21
    Last Post: 04-30-2008, 01:51 PM

Tags for this Thread