〔Coding style〕Reasons to add the curly brackets behind if / for / while in C/C++

Lynx Chang
Oct 5 · 2 min read

When the if / for / while statemant has only one line, you still need to add curly brackets. It makes your code structure clear and readable.

Reason 1: Multi-line macro

Like this:

if (condition)

At first glance, it’s fine, but if DO_SOMETHING itself is a macro, the person who defines the macro doesn’t wrap the whole paragraph with {}:

#define DO_SOMETHING int n=0\
printf("%d", n);

It will cause a logic error.

Reason 2: Changes on Git

Suppose you want to change the code to give a code review:

if (a > 0) a += b;

change into

if (a > 0) {
a += b;

Your logic only adds a line of c++, but for git you are modifying four lines, including the line that the if condition evaluates.
if (a > 0) a += b;if (a > 0) {
The person who reviews your code must confirm the conditions in the if conditional judgment, whether it is consistent with the original.

Reason 3: Consistency

If some if has curly brackets and some do not, this makes the coding style inconsistent. Moreover, you don’t have to remember this rule. As long as it is an if statement, all with curly brackets. This will keep the program consistent and reduce unnecessary thinking.

Reason 4: Readability

The existence of curly brackets make the boundaries of the code clear, which can make the burden on the eyes smaller.

Lynx Chang

Written by

Software Engineer

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade