+ 1

If else

What is difference between writing : else with {} and without {}

25th Apr 2018, 10:44 AM
Mohammadian Mohammad
Mohammadian Mohammad - avatar
2 Answers
+ 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.
25th Apr 2018, 11:30 AM
cyk
cyk - avatar
+ 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”; }
25th Apr 2018, 11:20 AM
Luigi
Luigi - avatar