Curly brace requirements for single vs multi-line
What you'll learn: How to decide when curly braces {} are optional or mandatory in your control structures.
In C, curly braces are like the walls of a room. They group multiple statements together into a single "block." However, C allows a shorthand that often trips up beginners: if a control structure (like an if statement or a for loop) only needs to execute exactly one statement, the braces are optional.
The "One-Room" Rule
Think of an if statement as a security guard. If you don't provide curly braces, the guard only watches the very next line of code. Everything after that first line is considered "outside" the guard's jurisdiction, regardless of how much you indent it.
#include <stdio.h>
int main() {
int temperature = 30;
// Single-line: Braces are optional
if (temperature > 25)
printf("It is hot outside.\n");
// Multi-line: Braces are MANDATORY
if (temperature > 25) {
printf("Turning on the fan...\n");
printf("Stay hydrated!\n");
}
// The Danger Zone: A common bug
if (temperature < 10)
printf("It is freezing!\n");
printf("Wear a coat.\n"); // This ALWAYS runs, even if it's hot!
return 0;
}
The Indentation Trap
In the "Danger Zone" example above, the compiler ignores your tabs and spaces. Even though "Wear a coat" is indented, the if statement only claims ownership over the "It is freezing" line because there are no curly braces. To the computer, the "Wear a coat" line is just a regular instruction that follows the if block, so it will print even if it is 100 degrees outside.
When to use braces
While you can omit braces for a single line, many professional style guides recommend using them every single time. Using braces prevents "dangling" statements and makes your code safer if you decide to add a second line of logic later. If you start with a single line and later add a second one without remembering to add the braces, you introduce a bug that can be very difficult to spot.
Key takeaway
Curly braces are optional for a single statement but mandatory for multiple statements; when in doubt, always use them to avoid logic errors.