User Tools

Site Tools


guides:programstyle:codeblocks

This is an old revision of the document!


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.

guides/programstyle/codeblocks.1595601003.txt.gz · Last modified: 2024/07/25 15:01 (external edit)