- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.