A compound statement is a list of statements enclosed by braces. There are many common ways of formatting the braces. Please be consistent with our local standard. When editing someone else's code, always use the style used in that code.
control {
statement;
statement;
}
The style above is called ``K&R style'', and is
preferred if you haven't already got a favorite.
With K&R style, the
else
part of an
if-else statement
and the
while
part of a do-while statement
should appear on the same line as the close brace.
With most other styles, the braces are always alone on a line.
When a block of code has several labels
(unless there are a lot of them),
the labels are placed on separate lines.
The fall-through feature of the C switch statement,
(that is, when there is no
break
between a code segment and the next
case
statement)
must be commented for future maintenance.
A lint-style comment/directive is best.
switch (expr) {
case ABC:
case DEF:
statement;
break;
case UVW:
statement;
/*FALLTHROUGH*/
case XYZ:
statement;
break;
}
Here, the last
break
is unnecessary, but is required
because it prevents a fall-through error if another
case
is added later after the last one.
The
default
case, if used, should be last and does not require a
break
if it is last.
Whenever an
if-else
statement has a compound statement for either the
if
or
else
section, the statements of both the
if
and
else
sections should both be enclosed in braces
(called fully bracketed syntax).
if (expr) {
statement;
} else {
statement;
statement;
}
(ex1)
and its mate are omitted:
if (ex1) {
if (ex2) {
funca();
}
} else {
funcb();
}
An if-else with else if should be written with the else conditions left-justified.
if (STREQ (reply, "yes")) {
statements for yes
...
} else if (STREQ (reply, "no")) {
...
} else if (STREQ (reply, "maybe")) {
...
} else {
statements for default
...
}
Do-while
loops should always have braces around the body.
Forever loops should be coded using the
for
(;;)
construct, and not the
while
(1)
construct.
Do not use braces for single statement blocks.
for (;;)
function();
Sometimes an
if
causes an unconditional control transfer
via
break
,
continue
,
goto
,
or
return
.
The
else
should be implicit and the code should not be indented.
if (level > limit)
return (OVERFLOW)
normal();
return (level);