Table of Contents
Compound Statements or Code Blocks
Short Answer
The body of all control structures should be enclosed in a code block. This rule applies to control structure bodies with a single simple statement.
Acceptable examples:
if (x > 5) { big = true; } for (i = 0; i < 10; i++) { cout << i << endl; } do { ProcessItem(count); } while ( count < 7);
Unacceptable examples:
if (x > 5) big = true; for (i = 0; i < 10; i++) cout << i << endl; do ProcessItem(count); while ( count < 7);
Discussion
In c/c++ statements can be grouped into a single statement using a code block or “curly braces”. The most common use of a code block is to extend the content of the body of a control structure to include more than one statement.
The syntax for an if statement is
if (boolean expression) statement;
Using a code block this is extended to
if (boolean expression) { statement_1; statement_2; ... statement_n; }
When the body of a control structure, such as if, is a single statement, code blocks are not required, however a common convention is to require code a code block for any control statement.
The main reason for this convention is that it allows programmers to modify code without introducing errors.
Consider the following example:
for(i = 0; i < 10; i++) Process(i);
Assume that Process is designed to output a message, however it has a bug in it so it does not produce any output. A first step at debugging may be to modify the loop as follows:
for(i = 0; i < 10; i++) cout << "In the loop, i = " << i << endl; Process(i);
Unfortunately, this has further broken the code. The programmer probably assumes that both lines following the for loop will be executed as the body of the loop, but this is not the case. Only the output line will be executed. Had the programmer followed the convention of always placing the body of a control structure in a code block, this would not be the case.
Failure to follow this convention leads to bugs so frequently that as of g++6, there is a flag to warn when this situation occurs (-Wmisleading-indentation).