+ 1
If else
What is difference between writing : else with {} and without {}
2 Respostas
+ 3
Basically, when you need several statements, or lines to be executed for your if or your else you need {}. That tells the system that it must execute everything between the { and } for your if or your else.
If you need ONLY one statement to be executed you do not need {}. You can put it but it is not necessary.
+ 2
When you’ve got to check a condition, if you’re omitting the {} the if / else if / else statements will only run the first code line, the {} are needed to run a bunch of code lines.
Example of one line conditional code:
if (a > b)
bigger = a;
else
bigger = b;
Example where {} are needed to run a bunch of lines of code:
if (a > b)
{
bigger = a;
std::cout << “A is bigger than B”;
}
else
{
bigger = b;
std::cout << “B is bigger than A”;
}