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?
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();