From the very beginning, the C language allowed omitting curly braces for a single statement within an if statement. This made the code more compact but led to many non-obvious errors, especially when extending and modifying the code. The historical reason is space-saving and simplicity of syntax for minimalist cases.
The problem arises when a developer forgets that without braces, if controls only the first expression following it: all subsequent ones are executed unconditionally, even when this may not be visually apparent. This style leads to hidden bugs that are difficult to identify while reading the code and errors arising from forgotten indentation or added new lines.
The solution is to always use curly braces, even if there is only one statement. This enhances both readability and safety of the code.
Code example:
// Bad: if (x > 0) do_something(); do_other(); // Always executed // Better: if (x > 0) { do_something(); do_other(); }
Key features:
Does indentation (tab/space) affect the scope of if?
No, in C, the scope is defined only by braces, not by indentation.
What behavior will this code have?
if (a > 0) fun1(); fun2();
fun1() will be called only if a > 0. fun2() will always be called regardless of the condition.
What are the consequences if a new line is added without braces?
This code may change behavior and lead to errors that are visually hard to detect, as indentation does not protect against compilation errors.
A developer added a second statement to a single-line if, forgetting to add braces.
if (user) initialize(); log_access();
Pros:
Cons:
A developer always uses curly braces even for a single statement:
if (user) { initialize(); log_access(); }
Pros:
Cons: