0

is this info correct?

in c++ course it is written that if - if /else condition contains only one statement then curly braces can be ommited? but i have written some. program which contains two statements & they ran fine, why?

26th Oct 2017, 4:44 PM
shobhit
shobhit - avatar
1 Réponse
+ 4
Because one ran as part of the IF statement, and the other ran by itself without a condition. That's why it still worked. if(this condition true) cout<<"I didn't need braces!"; // this ran as part of the IF statement cout<<"I did need braces!"; // this ran by itself, NOT part of IF statement However, it's good practice to always use curly braces even if it's only one statement. This prevents potential errors, the issue you're having right now, and makes it more readable / easier for others that are dealing with your code. Overall, it's just safer and more organized. With that being said, yes, you can omit if you want; no one will force you into good practices unless you start working for someone / a team. Don't get fired because of bad practices. Trust me, for a LONG time I was a solo programming, so I formed a LOT of bad habits. When you don't have to work with others and no one will see your code, it's easy to be lazy and not go with the best practices. However, it's a pain when you find yourself in a corporate setting with other programmers and you appear sloppy with your code. EXAMPLE: if(this condition true) cout<<"I didn't need braces!"; else cout<<"I did need braces!"; if(condition is false) cout<<"it was false!"; ---------------------------------------- Best practice: if(this condition true) { // stuff } else { // stuff } if(this condition true) { cout<<"asdasd"; }
26th Oct 2017, 4:56 PM
AgentSmith