Blocks

The if selection statement expects only one statement in its body. Similarly, the if and else parts of an if...else statement each expect only one body statement. To include several statements in the body of an if or in either part of an if...else, enclose the statements in braces ({ and }). A set of statements contained within a pair of braces is called a block.


Image Software Engineering Observation 4.2

A block can be placed anywhere in a program that a single statement can be placed.


The following example includes a block in the else part of an if...else statement.

if ( studentGrade >= 60 )
   cout << "Passed. ";
else
{
   cout << "Failed. ";
   cout << "You must take this course again. ";
}

In this case, if studentGrade is less than 60, the program executes both statements in the body of the else and prints

Failed.
You must take this course again.

Notice the braces surrounding the two statements in the else clause. These braces are important. Without the braces, the statement

cout << "You must take this course again. ";

would be outside the body of the else part of the if and would execute regardless of whether the grade was less than 60. This is a logic error.

Just as a block can be placed anywhere a single statement can be placed, it’s also possible to have no statement at all, which is called a null statement or an empty statement. The null statement is represented by placing a semicolon (;) where a statement would normally be.


Image Common Programming Error 4.1

Placing a semicolon after the condition in an if statement leads to a logic error in single-selection if statements and a syntax error in double-selection if...else statements (when the if part contains an actual body statement).


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset