A question about if/else statements

Hello everyone,

So I'm starting to learn how to use if/else, and while doing a practice program, i came across an error on my part where I tried to assign or declare a variable while inside the if/else brace, and it didn't work out, or it said the given variable was not assigned, yet if the variable was assigned outside the if/else, works fine. However, when I compared this to the "while" loop, i noticed in the book that you can declare and assign variables inside the loop. Thus, my question is, would I be correct in thinking that the if/else lacks the capability to declare and assign variables inside it while the while loop and other loops such as the "for" loop can?

-Thank you all for your time.
You can declare variables in any block, if/else blocks included.
The scope of a variable is limited to the block it's defined in. So, if you try to do this:
1
2
3
4
/*...*/{
    int a=42;
}
a++; //Error. a is not declared. 

But this works:
1
2
3
4
5
int a;
/*...*/{
    a=42;
}
a++;

If this doesn't answer your question, please post code and error messages.
Ok, so this is my test code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include<iostream>
#include<string>


using namespace std;

int main ()


{


int x;

cin >> x;

	if(x > 1)
	
		cout << "good.\n";
		
	else
		
		cout << "bad.\n";
	
}


The top code will compile normally. However, when I try something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include<iostream>
#include<string>


using namespace std;

int main ()


{


int x;

cin >> x;

	if(x > 1)
	
		int y = 2;
	
		cout << "good.\n";
		cout << y;
		
	else
		
		cout << "bad.\n";
	
}


i get a message in the form of this: http://imageshack.us/photo/my-images/6/picpi.png/

My question is that when I assigned int y = 2; in side the "if" bracket, it wont compile.
If you use if/else without {braces} They will only execute the next 1 line.

That is:

1
2
3
4
5
if(a)
  b();  // this will happen if 'a' is true
c();  // this will happen always, it is not part of the above if statement
else  // this will error, because the previous line did not have anything to do with an 'if'
  d();


If you want multiple commands in an if block, you need to use braces:
1
2
3
4
5
6
7
if(a)
{  // now everything inside the braces is part of the 'if'
  b();  // will happen if 'a' is true
  c();  //  ditto
} // our 'if' ends here
else  // now this will work, because we just finished an 'if'
  d();
Last edited on
Oh ok, now i get it, thanks alot!
Topic archived. No new replies allowed.