Very easy C++ question

Associate
Joined
17 Nov 2008
Posts
1,680
Just a small thing I can't remember how to do. I have an integer value which I change in an if statement, and I also want the value to change outside the if statement.
 
To do with scope of where the variable is first declared. If it's declared outside the IF statement then it will keep its value, e.g

Code:
int a = 4;
if(a < 10)
{
     int b = 4;
     a = 100;
}

// a == 100 here
// b is dead

If you declare a variable inside the if, then it is killed when the scope changes.
 
Last edited:
To do with scope of where the variable is first declared. If it's declared outside the IF statement then it will keep its value, e.g

Code:
int a = 4;
if(a < 10)
{
     int b = 4;
     a = 100;
}

// a == 100 here
// b is dead

If you declare a variable inside the if, then it is killed when the scope changes.
Thanks, I think there is something else stopping it working then.
 
To do with scope of where the variable is first declared. If it's declared outside the IF statement then it will keep its value, e.g

Code:
int a = 4;
if(a < 10)
{
     int b = 4;
     a = 100;
}

// a == 100 here
// b is dead

If you declare a variable inside the if, then it is killed when the scope changes.
^^ this
 
Finally got my program finished, been working on it solidly 10 hours today.

Get it here if you want to take a look. Hangman isn't very interesting but still a challenge since I only started programming last September.

I uploaded the code too so any tips would be appreciated :). I have a tic tac toe one to make too.
 
Finally got my program finished, been working on it solidly 10 hours today.

Get it here if you want to take a look. Hangman isn't very interesting but still a challenge since I only started programming last September.

I uploaded the code too so any tips would be appreciated :). I have a tic tac toe one to make too.

My main comment would be remember that C++ is object orientated, you're not benefiting from that at all with your program. Also although you seem to have tried to do this in places, be sure to try and keep your main function relatively small - mainly so it's easier to read.

Avoid passing massive strings about, so for your "draw_hangman" function you could probably replace those long print statements with a for loop if you tried.
 
Back
Top Bottom