Why is it considered a bad practice to omit curly braces in C/C++?


In C++ we can omit the curly braces after if-else statements, or after any loop. If we do not use curly braces then only one statement after the if-else or loop will be considered under that block. For example −

if(condition) {
   Line 1
   Line 2
}

if(condition)
Line 1
Line 2

In the first case, the Line1 and Line2 both are in the if block. But in the second condition, the Line1 is in if block but Line2 is not in if block. So we can omit curly braces only there is a single statement under if-else or loop.

Sometimes for debugging purpose we just make a line commented. Using this we check the effect of output without that statement. In that time the if-else or loops without braces makes some troubles. For example −

if(condition) {
   Line 1
}
Line2

if(condition)
Line 1
Line 2

Here in both of the cases, the Line1 is in the if block but Line2 is not in the if block. So if the condition fails, or it satisfies the Line2 will be executed always. Now if the situation is like below for some debugging purpose, then it may generate some problems.

if(condition)
//Line 1
Line 2

If the Line1 is commented, we just think that it is fine, but in this case, the compiler thinks that Line2 is in the if block, but that is wrong. If we use braces, then there is no problem.

Updated on: 30-Jul-2019

725 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements