Control flow
If statement
if statement
Syntax:
if (condition) { // do something }
Condition:
- A boolean expression that evaluates to true or false.
- Any non-zero value is considered true, and zero is considered false.
If the condition is true, the code block inside the if statement will be executed.
If the condition is false, the code block inside the if statement will be skipped.
Examples
int a = 10;
if (a > 0) {
<< "a is positive" << endl;
cout }
If the statement takes only one line, you can use the following syntax:
if (a > 0)
<< "a is positive" << endl;
cout << "This line is always executed"; cout
Condition can be any expression.
float b = 0.5;
if (b) { // not recommended, make the code less readable
<< "b is true" << endl;
cout }
if-else statement
Syntax:
if (condition) { // do something } else { // do something else }
It will execute the code block inside the if statement if the condition is true.
It will execute the code block inside the else statement if the condition is false.
int a = -10;
if (a > 0) {
<< "a is positive" << endl;
cout } else {
<< "a is negative" << endl;
cout }
If there’s only one statement, you can use the following syntax:
if (condition) statement1;
else statement2;
To make the code more readable, avoid using ambiguous sytntax.
For example, when will “Where I’m?” be printed?
if (num < 10)
if (num < 5)
<< "The number is less than 5" << endl;
cout else
<< "Where I'm?" << endl; cout
else-if statement
Syntax:
if (condition1) { // do something } else if (condition2) { // do something else } else { // do something else }
It will execute the code block inside the if statement if the condition1 is true.
It will execute the code block inside the else if statement if the condition2 is true.
It will execute the code block inside the else statement if the condition1 and condition2 are false.
?:
operator (ternary operator)
Syntax:
? expression1 : expression2; condition
It will return expression1 if the condition is true.
It will return expression2 if the condition is false.
When to use ?:
operator?
- When you want to assign a value to a variable based on a condition.
- When you want to return a value from a function based on a condition.
int a = 10;
int b = 20;
int c = a > b ? a : b; // c = 20
Comparison operators
==
: equal to!=
: not equal to<
: less than>
: greater than<=
: less than or equal to>=
: greater than or equal to
These operators return true if the condition is true, otherwise false.
Logical operators
&&
: and, returns true if both operands are true.||
: or, returns true if either operand is true.!
: not, returns true if the operand is false.^
: xor, returns true if both operands are different.
Precedence of logical operators: !
> &&
> ||
.
int a = 10;
int b = 20;
int c = 30;
// the next line is equivalent to (a > 0 && b > 0) || c > 0
if (a > 0 && b > 0 || c > 0) {
<< "a, b are positive or c is positive" << endl;
cout }
Statement scope
Statement scope is the scope of a statement. Usually scope is defined by {}
.
- A variable defined outside a statement scope can be used in the statement scope and its nested statement scopes.
- A variable defined in a statement scope cannot be used in the parent statement scope.
int a = 10;
if (a > 0) {
int b = 20;
= 100;
a << "b = " << b << endl;
cout }
<< "a = " << a << endl; // a = 100
cout << "b = " << b << endl; // error: b is not defined cout
Switch statement
Syntax:
switch (expression) { case constant1: // do something break; // don't forget this! case constant2: // do something break; // don't forget this! default: // do something break; // don't forget this! }
The code block executes when the value of the expression matches the constant in the case.
The
break
statement is used to terminate the switch statement.- If you don’t use
break
, the code block inside the case will be executed sequentially.
- If you don’t use
The
default
statement is executed if none of the cases are matched.
Iterations
while loop
Syntax:
while (condition) { // do something }
It will execute the code block inside the while loop as long as the condition is true.
The condition is evaluated before the code block inside the while loop is executed.
int i = 0;
while (i < 10) {
<< "i = " << i << endl;
cout ++;
i} // 10 will not be printed
do-while loop
Syntax:
do { // do something } while (condition);
It will execute the code block inside the do-while loop at least once.
The condition is evaluated after the code block inside the do-while loop is executed.
int i = 0;
do {
<< "i = " << i << endl;
cout ++;
i} while (i < 10); // 10 will be printed
For loop
Syntax:
for (initialization; condition; increment) { // do something }
The variable defined in the initialization part is only visible in the for loop.
Example:
int sum = 0;
for (int i = 0; i < 10; i++) {
+= i;
sum }
<< "sum = " << sum << endl; // ok, sum is defined outside the loop
cout << "i = " << i << endl; // error: i is not defined cout
The increment part of the for
loop can be omitted.
int sum = 0;
for (int i = 0; i < 10; ) {
+= i;
sum ++;
i}
The initialization part of the for
loop can be omitted. In this case, i
can be used after the loop.
int sum = 0;
int i = 0;
for (; i < 10; i++) {
+= i;
sum }
The increment part of the for
loop can be other expressions.
int sum = 0;
for (int i = 0; i < 10; i += 2) {
+= i; // sum the even numbers from 0 to 9
sum }
for
loop vs while
loop
The two loops are equivalent, except the scope of the variable i
.
int i = 0;
while (i < 10) {
<< "i = " << i << endl;
cout ++;
i} // i can be used after the loop
for (int i = 0; i < 10; i++) {
<< "i = " << i << endl;
cout } // i can't be used after the loop
Endless loop
Sometimes we want to create a loop that will run forever. For example, we want to create a game that will run until the player wins.
while (true) {
// game logic
}
for (;;) {
// game logic
}
Sometimes your program runs in by mistake, be careful.
// mistake 1: size_t is unsigned, so it will not be less than 0
size_t i = 10;
while (i > 0) {
<< "i = " << i << endl;
cout --;
i}
// mistake 2: the condition is an assignment to flag, it will always be true
bool flag = true;
int count = 0;
// mistake: flag = true is an assignment, not a comparison
while (flag = true) {
++;
countif (count == 5) {
= false;
flag }
}
Value of expression
Each expression in C++ has a value,
3+4
has the value7
.a > b
has the valuetrue
orfalse
.a+b
has the value ofa+b
.a = b
has the value ofb
.
The assignment operator =
has the lowest precedence, so a = b = c
is equivalent to a = (b = c)
. see cppreference.
// example used to show the value of expression
// not recommended to use this way
int a = 10;
int b = 20;
int c = a = b; // c = 20, a = 20, b = 20
// equivalent to int c = (a = b);
Jump statements
break
statement
The break
statement is used to terminate the loop or switch statement.
for (int i = 0; i < 10; i++) {
if (i == 5) {
break;
}
<< "i = " << i << endl;
cout }
// outputs: 0 1 2 3 4
int i = 0;
while (true) {
if (i == 5) {
break;
}
<< "i = " << i << endl;
cout ++;
i}
// outputs: 0 1 2 3 4
continue
statement
The continue
statement is used to skip the rest of the code block inside the loop and continue the loop.
- In
while
ordo-while
loop, the next iteration starts after the condition is evaluated. - In
for
loop, the increment part is executed first, then the condition is evaluated.
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
<< "i = " << i << endl;
cout }
// 6 is output directly because the continue statement is executed when i == 5.
// outputs: 0 1 2 3 4 6 7 8 9
Example:
int i = 0;
while (i < 10) {
if (i == 5) {
continue;
}
<< "i = " << i << endl;
cout ++;
i}
// outputs: 0 1 2 3 4 then endless loop
int i = 0;
while (i < 10) {
<< "i = " << i << endl;
cout ++;
iif (i == 5) {
continue;
}
}
// outputs: 0 1 2 3 4 6 7 8 9
goto
statement (not recommended)
The goto
statement is used to jump to a label.
To define a label, you can use the following syntax:
:
label{
// do something
}
If the label only has one statement, you can use the following syntax:
:
label// do something
Labels are often defined in the same function scope of the goto
statement. It can be defined before or after the goto
statement.
To jump to a label, you can use the following syntax:
goto label;
Example:
float mysquare(float value)
{
float result = 0.0f;
if(value >= 1.0f || value <= 0)
{
<< "The input is out of range." << endl;
cerr goto EXIT_ERROR;
}
= value * value;
result return result;
:
EXIT_ERROR//do sth such as closing files here
return 0.0f;
}
References
- cppreference
- Prof. Shiqi Yu’s lecture notes
- A tour of C++ by Bjarne Stroustrup, the creator of C++.