Why are there so many curly braces in the nested if 'try it yourself'. Can't the code be completed with a single pair of them? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why are there so many curly braces in the nested if 'try it yourself'. Can't the code be completed with a single pair of them?

19th Jan 2019, 10:57 AM
Haider Rassiwala
8 Answers
+ 4
HonFu i think its regarding the java if-statement tutoral?
19th Jan 2019, 12:20 PM
D_Stark
D_Stark - avatar
+ 4
Haider Rassiwala if(dogs==11){do somthing;} else if(dogs>=15){doSomthing;} else{do this if all conditions return false;}
19th Jan 2019, 12:26 PM
D_Stark
D_Stark - avatar
+ 4
No that's not how it's done. An if is connected to a single statement: if(2>1) printf("yep"); if you want to make more than one statement part of that if, you need braces. if (2>1) { statement1; 2; }
19th Jan 2019, 12:27 PM
HonFu
HonFu - avatar
+ 3
Not really the braces are there to keep things in order If(true){do somthing} _____________________________ If(false){this gets ignored} else{do somthing} if one of the above statment were nested inside a if statements body then this outside condition must return true for the inner statments to execute.
19th Jan 2019, 12:14 PM
D_Stark
D_Stark - avatar
+ 2
We can not know what code you are talking about. Is it in C or C++? Yeah, when there's only one statement in a loop or condition, you can do without the braces. Maybe they left them in anyway in order not to confuse beginners. Also it is sometimes recommended to always write them even if you don't have to: Code gets changed over time. What's one statement now may be two or three later, and easily you forget to add the braces or put them in the wrong places and then suddenly nothing works anymore.
19th Jan 2019, 12:15 PM
HonFu
HonFu - avatar
+ 2
Okay! I think this course is going way to fast. But i am also studying from a youtube channel and a book for beginners.
19th Jan 2019, 12:28 PM
Haider Rassiwala
+ 2
For my taste, the tutorials are also too consice, I need some reading on the side. ;-) Don't worry, don't hurry, one step at a time!
19th Jan 2019, 12:44 PM
HonFu
HonFu - avatar
0
No, it is about C language. Let me clarify it more properly. Before writing every another *else* function do i have to put curly braces. For example. { If (dogs= 11) {If else(dogs >=15) {If else(dogs >= 20)
19th Jan 2019, 12:23 PM
Haider Rassiwala