Formatting Compound Statements

Compound statements are statements followed by one or more statements enclosed with braces. A function block is an obvious example of a compound statement. Control statements (while, for) and selection statements (if, switch) are also examples of compound statements.

Omitting braces is a common C coding practice when only one statement follows a control or selection statement. However, you must use braces for all compound statements for these reasons:

  • The absence of braces can cause errors.

  • Braces ensure that all compound statements are treated the same way.

  • In the case of nested compound statements, the use of braces clarifies the statements that belong to a particular code block.

  • Braces make subsequent modifications easier.

Refer to these guidelines when formatting compound statements:

  • Always have one statement per line within a compound statement.

  • Always use braces to contain the statements that follow a control statement or a selection statement.

  • Braces should be aligned with the initial control or selection statement.

  • Logical expressions evaluated within a control or selection statement should be broken up across multiple lines if they do not fit on one line. When breaking up multiple logical expressions, do not begin a new line with the logical operator; the logical operator must remain on the preceding line.

  • When evaluating multiple logical expressions, use parentheses to explicitly indicate precedence.

  • Never declare variables within a compound statement, except function blocks.

  • Use braces for all compound statements.

  • Place each opening or closing brace, { or }, on a separate line.