[ fromfile: controlstructures.xml id: condexpr ]
Every programming language has at least one control structure that enables the flow of the program to branch depending on the outcome of a boolean condition.
C and C++ have if
and switch
.
The if
statement typically has the following form.
if(boolExpression) statement
It can have an optional else
attached.
if(boolExpression) statement1 else statement2
Conditional statements can be nested,
an else
or else if
clause is activated when the boolExpression of the immediately preceding open if
evaluates to false.
An if
without an else
can be closed by enclosing the if
statement in braces {}
, making it a compound statement.
switch
switch
is another branching construct, which permits the execution of different code depending the value of a parameter.
switch(integralExpression) { case value1: statement1; break; case value2: statement2; break; ... case valuen: statementn; break; default: defaultStatement; } nextStatement;
When the switch
causes a jump to a case
label whose value matches the integralExpression, statements are executed from that point on until the end of the switch
block or a branching statement (e.g. break
) is reached.
Each case
label, except default
, must be an integer constant.[77]
Any switch
statement such as the previous one can be rewritten as a long if ... else
statement.
However, the runtime performance of a switch
is considerably better because it requires only a single comparison, and performs only one branch.
if(integralExpression == value1) statement1; else if(integralExpression == value2) statement2; ... else if(integralExpression == valuen) statementn; else defaultStatement;
[77] case
labels are not the same as goto
labels, which are used as destinations for the infamous goto
statement. goto
labels must be identifiers. In particular, they cannot be integers.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |