Professional Documents
Culture Documents
Conditional Statements
Conditional Statements
Conditional Statements
1. if Statement
The general form of the if statement is:
if (expression)
{
statement;
}
where:
if is a reserve word in C++.
expression is a relational or Boolean expression that evaluates
to a true (1) or false (0) value.
statement may either be a single C++ statement or a block of
C++ statements.
2. if else Statement
The general form of if else statement is:
if (expression)
{
statement_1;
}
else
{
statement_2;
}
where:
if and else are reserve words in C++.
expression is a relational or Boolean expression that evaluates
to a true (1) or false (0) value.
statement_1 and statement_2 may either be a single C++
statement or a block of C++ statements.
3. if else if Ladder
A common programming construct in C++ is the if else if ladder.
The general form of if else if ladder is:
if (expression_1)
{
statement_1;
}
else if (expression_2)
{
statement_2;
}
else if (expression_3)
{
statement_3;
}
else
{
statement_else;
}
Where:
if and else are reserve words in C++.
expression_1 up to expression_n is a relational or Boolean
expression that evaluates to a true (1) or false (0) value.
statement_1 up to statement_else may either be a single C++
statement or a block of C++ statements.
4. Nested if Statement
One of the most confusing aspects of the if statement in any
programming language is nested ifs. A nested if is an if statement that is the
object of the either an if or else. This is sometimes referred to as an if within
an if.
The reason why nested if is so confusing is that it can be difficult to
know about what else associates with what if.
Fortunately, C++ provides a very simple rule for resolving this type of
situation. In C++, the else is linked to the closest preceding if that does not
already have an else statement associated with it.
5. switch Statement
The switch statement is a multiple branch decision statement.
The general form of the switch statement is:
switch (variable)
{
case constant_1:
{
statement_1;
break;
}
case constant_2:
{
statement_2;
break;
}
case constant_3:
{
statement_3;
break;
}
default:
{
statement_default;
}
}
In a switch statement, a variable is successively tested against a list of
integer or character constants. If a match is found, a statement or block of
statements is executed. The default part of the switch is executed if no matches are
found.
According to Herbert Schildt (1992), there are three important things to know
about switch statements:
1. The switch differs from if statements in such a way that switch can only
test for equality whereas if can evaluate a relational or logical expression.
2. No two case constants in the same switch can have identical values. Of
course, a switch statement enclosed by an outer switch may have case
constants that are the same.
3. If character constants are used in the switch, they are automatically
converted to their integer values.