Statements in which an if structure is contained inside another if structure are commonly called

Skip to main content

This browser is no longer supported.

Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.

Compound Statements (Blocks)

  • Article
  • 08/03/2021
  • 2 minutes to read

In this article

A compound statement consists of zero or more statements enclosed in curly braces ({ }). A compound statement can be used anywhere a statement is expected. Compound statements are commonly called "blocks."

Syntax

{ [ statement-list ] }

Remarks

The following example uses a compound statement as the statement part of the if statement (see The if Statement for details about the syntax):

if( Amount > 100 )
{
    cout << "Amount was too large to handle\n";
    Alert();
}
else
{
    Balance -= Amount;
}

Note

Because a declaration is a statement, a declaration can be one of the statements in the statement-list. As a result, names declared inside a compound statement, but not explicitly declared as static, have local scope and (for objects) lifetime. See Scope for details about treatment of names with local scope.

See also

Overview of C++ Statements

Feedback

Submit and view feedback for

The if-then Statement

The if-then statement is the most basic of all the control flow statements. It tells your program to execute a certain section of code only if a particular test evaluates to true. For example, the Bicycle class could allow the brakes to decrease the bicycle's speed only if the bicycle is already in motion. One possible implementation of the applyBrakes method could be as follows:

void applyBrakes() {
    // the "if" clause: bicycle must be moving
    if (isMoving){ 
        // the "then" clause: decrease current speed
        currentSpeed--;
    }
}

If this test evaluates to false (meaning that the bicycle is not in motion), control jumps to the end of the if-then statement.

In addition, the opening and closing braces are optional, provided that the "then" clause contains only one statement:

void applyBrakes() {
    // same as above, but without braces 
    if (isMoving)
        currentSpeed--;
}

Deciding when to omit the braces is a matter of personal taste. Omitting them can make the code more brittle. If a second statement is later added to the "then" clause, a common mistake would be forgetting to add the newly required braces. The compiler cannot catch this sort of error; you'll just get the wrong results.

The if-then-else Statement

The if-then-else statement provides a secondary path of execution when an "if" clause evaluates to false. You could use an if-then-else statement in the applyBrakes method to take some action if the brakes are applied when the bicycle is not in motion. In this case, the action is to simply print an error message stating that the bicycle has already stopped.

void applyBrakes() {
    if (isMoving) {
        currentSpeed--;
    } else {
        System.err.println("The bicycle has already stopped!");
    } 
}

The following program, IfElseDemo, assigns a grade based on the value of a test score: an A for a score of 90% or above, a B for a score of 80% or above, and so on.

class IfElseDemo {
    public static void main(String[] args) {

        int testscore = 76;
        char grade;

        if (testscore >= 90) {
            grade = 'A';
        } else if (testscore >= 80) {
            grade = 'B';
        } else if (testscore >= 70) {
            grade = 'C';
        } else if (testscore >= 60) {
            grade = 'D';
        } else {
            grade = 'F';
        }
        System.out.println("Grade = " + grade);
    }
}

The output from the program is:

You may have noticed that the value of testscore can satisfy more than one expression in the compound statement: 76 >= 70 and 76 >= 60. However, once a condition is satisfied, the appropriate statements are executed (grade = 'C';) and the remaining conditions are not evaluated.

Presentation on theme: "Nested if statements When one if/else structure is contained inside another if/else structure is called a nested if/else. if (grade > 60) if (grade > 70)"— Presentation transcript:

1 nested if statements When one if/else structure is contained inside another if/else structure is called a nested if/else. if (grade > 60) if (grade > 70) printf(“You passed”); else printf(“You passed but need a tutor”); printf(“You failed”);

2 else if Usually you try to nest within the else statement. Note the indentation. if (grade > 70) printf(“You passed”); else if (grade > 60) printf(“You passed but need a tutor”); else printf(“You failed”);

3 && - Logical AND (section 4.10)
if ((total > 50) && (status == 0)) printf(“Your shipping will be free\n”); When using the and operator (&&), both expressions must be true for the compound statement to be true. truth table

4 || - Logical OR (section 4.10)
if ((total > 50) || (status == 0)) printf(“Your shipping will be free\n”); When using the or operator (||), at least one expression must be true for the compound statement to be true. truth table

5 more on && and || Can be used to reduce nesting
&& has higher precedence evaluation stops once truth or falsehood is known - in the example below, if semesterAverage > 90 finalExam will not get tested if ((semesterAverage > 90) || (finalExam > 90)) printf(“Student gets an a\n”);

6 logical negation ! (section 4.10)
if !(grade == goal) printf(“You missed your goal\n”); ! has high precedence so you must use parenthesis In most cases you can avoid using the logical negation by expressing the condition differently with an appropriate relational operator. Note: its a unary operator

7 #define The #define preprocessor directive creates symbolic constants (it has another use we may talk about later) #define PI Would replace all subsequent occurrences of the symbolic constant PI with the numeric constant , in the code

8 #define (cont’d) Used to avoid “magic numbers” in code
Unlike variables, you should not change the value of a symbolic constant Should be used before your variable declarations Should be in ALL CAPS, except if you use Hungarian Notation e.g. #define iMY_CONSTANT 3600

9 Avoid magic numbers! Magic numbers are actual numbers you use throughout your code e.g. your divisor of 10000 If you need to change them, at worst it takes time to find all the occurrences, at worst you may miss a few If you use #define, you only need to change the value once at the top of your code E.g #define f_ACCEPTABLE_THRESHOLD

10 reading We have already covered For next class chapter 1 chapter 2
sections section 4.10, 4.11 section 13.3 For next class 4.7

When an if statement is nested in the if clause of another statement?

A nested if statement is an if statement placed inside another if statement. Nested if statements are often used when you must test a combination of conditions before deciding on the proper action.

When you use nested if statements you must pay careful attention to placement of any else clauses True False?

When you use nested if statements, you must pay careful attention to placement of any else clauses. In the switch structure, break is followed by one of the possible values for the test expression and a colon. Computers contain switches that are set to on or off.

When writing a statement with the two line format you must be sure to type a semicolon?

When writing a statement with the two-line format, you must be sure to type a semicolon at the end of the first line in order to ensure accurate results. Although it is possible to block statements that depend on an if, you cannot likewise block statements that depend on an else.

What do we call a series of if statements that determine whether a value falls within a specified range?

used to negate the result of any Boolean expression. range check. A series of if statements that determine whether a value falls within a specified range.