What does a ‘for’ loop without curly braces do?

Without curly braces, only the first statement following the loop definition is considered to belong to the loop body.

Notice that in your example, printf is only called once. Though its indentation matches the previous line, that’s a red herring – C doesn’t care. What it says to me is that whoever wrote the code probably forgot the braces, and intended the printf statement to be part of the loop body.

The only time I would leave out the curly braces is when writing a one-line if statement:

if (condition) statement;
do_something_else();

Here, there’s no indentation to introduce ambiguity about whether the statement on the second line is actually supposed to belong to the body of the if. You would likely be more confident when reading this that it’s working as intended.

Leave a Comment