Chapter 03 Control Flow
1. Algorithm
Algorithm describes the control of the flow, such as which expression computes first, whether to compute some expressions or repeating computing some expressions several times.
We use statement to describe and implement algorithm.
Sometimes we choose to first draw a flowchart to help us clarify the algorithm before we actually write some code to implement it.
2. Sequential Execution
- Expression Statement
An expression statement is just an expression with
;
behind it, which does the same thing as the expression but is a complete statement.
- Compound Statement
Compound statement is composed of several statements, with
{
before them and}
behind them, which is also called block.
- Blank statement
Blank statement is just
;
, which does nothing at all. What it only does is that it plays a grammar role or syntax role at a place where it needs nothing but a statement to make it grammatically appropriate.
3. Selection Control
Selection control also called branching control allows us to execute some statements selectively according to some conditional judgments, which is implemented using if-statement or switch-statement.
3.1 If-statement
if (<boolean-expression>) <statement(s)>
if (<boolean-expression>) <statement(s)1> else <statement(s)2>
C++ doesn’t take writing style into consideration when reading your code.
Unlike python, indent makes no sense in C++ other than make your code easier for other coder to understand.
Each
else
is coupled with its nearestif
.
3.2 Switch-statement
switch (<integral-expression>){
case <integral-constant-expression1>: <statement-sequence1>
case <integral-constant-expression2>: <statement-sequence2>
......
case <integral-constant-expressionn>: <statement-sequencen>
[default: <statement-sequencen+1>]
}
Integral constant expressions’ values can’t be the same with each other.
Statement sequence can either be a statement or a block without parentheses, and regularly end with a break statement.
Rules for execution:
- Evaluate the integral expression to get an integer value.
- Compare the value with all the following cases one by one until the integral constant expression with the same value.
- Execute the statement sequence behind it until it reach the end or encounter a break statement.
- If there’s no corresponding case, execute the statement sequence behind default if there exists one.