creating variables inside an if statement

This is a discussion on creating variables inside an if statement within the C++ Programming forums, part of the General Programming Boards category; hello friends, is it a good or a bad technique to create variables inside an if statement? for example i ...

  1. #1
    nik
    nik is offline
    Registered User
    Join Date
    Nov 2010
    Posts
    44

    creating variables inside an if statement

    hello friends,

    is it a good or a bad technique to create variables inside an if statement?

    for example

    i have

    Code:
    if (choice == something){
    
         here is one program
    }
    else{
    
       here is another program
    }
    
    }
    there are two different programs, each of them has different variables, should i declare them before the first if statement or should i declare each of them in its own if statement?

    thanks in advance

  2. #2
    Registered User
    Join Date
    Aug 2010
    Location
    Poland
    Posts
    682
    You should create variables where they are needed. If you don't use it before the if statement, don't declare it there.
    I never put signature, but I decided to make an exception.

  3. #3
    nik
    nik is offline
    Registered User
    Join Date
    Nov 2010
    Posts
    44
    thanks for your answer kmdv

    one last question, if there are similar variables in both programs, is it better to put them out of the if statement or it really doesn't matter?

  4. #4
    and the hat of sweating
    Join Date
    Aug 2007
    Location
    Toronto, ON
    Posts
    3,545
    Based on the code you posted, I'm guessing you mean "if block" instead of "program"?

    If your variables are only used inside those blocks, then I would declare them inside the if/else blocks. I try to keep variable scope as small as possible.
    "I am probably the laziest programmer on the planet, a fact with which anyone who has ever seen my code will agree." - esbo, 11/15/2008

    "the internet is a scary place to be thats why i dont use it much." - billet, 03/17/2010

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Help with Variables & updating Variables
    By DrC in forum C Programming
    Replies: 9
    Last Post: 01-30-2011, 02:46 AM
  2. bizarre print statement glitch
    By spongefreddie in forum C Programming
    Replies: 4
    Last Post: 09-23-2010, 11:39 AM
  3. Replies: 2
    Last Post: 04-13-2010, 04:14 PM
  4. Problems with string variables in an IF statement
    By Calef13 in forum C++ Programming
    Replies: 5
    Last Post: 12-30-2005, 10:40 PM
  5. Uh-oh! I am having a major switch problem!
    By goodn in forum C Programming
    Replies: 4
    Last Post: 11-01-2001, 04:49 PM

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