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) {
cout << "a is positive" << endl;
}If the statement takes only one line, you can use the following syntax:
if (a > 0)
cout << "a is positive" << endl;
cout << "This line is always executed";Condition can be any expression.
float b = 0.5;
if (b) { // not recommended, make the code less readable
cout << "b is true" << endl;
}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) {
cout << "a is positive" << endl;
} else {
cout << "a is negative" << endl;
}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)
cout << "The number is less than 5" << endl;
else
cout << "Where I'm?" << endl;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:
condition ? expression1 : expression2;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 = 20Comparison 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) {
cout << "a, b are positive or c is positive" << endl;
}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;
a = 100;
cout << "b = " << b << endl;
}
cout << "a = " << a << endl; // a = 100
cout << "b = " << b << endl; // error: b is not definedSwitch 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
breakstatement 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
defaultstatement 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) {
cout << "i = " << i << endl;
i++;
} // 10 will not be printeddo-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 {
cout << "i = " << i << endl;
i++;
} while (i < 10); // 10 will be printedFor 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++) {
sum += i;
}
cout << "sum = " << sum << endl; // ok, sum is defined outside the loop
cout << "i = " << i << endl; // error: i is not definedThe increment part of the for loop can be omitted.
int sum = 0;
for (int i = 0; i < 10; ) {
sum += i;
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++) {
sum += i;
}The increment part of the for loop can be other expressions.
int sum = 0;
for (int i = 0; i < 10; i += 2) {
sum += i; // sum the even numbers from 0 to 9
}for loop vs while loop
The two loops are equivalent, except the scope of the variable i.
int i = 0;
while (i < 10) {
cout << "i = " << i << endl;
i++;
} // i can be used after the loopfor (int i = 0; i < 10; i++) {
cout << "i = " << i << endl;
} // i can't be used after the loopEndless 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) {
cout << "i = " << i << endl;
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) {
count++;
if (count == 5) {
flag = false;
}
}Value of expression
Each expression in C++ has a value,
3+4has the value7.a > bhas the valuetrueorfalse.a+bhas the value ofa+b.a = bhas 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;
}
cout << "i = " << i << endl;
}
// outputs: 0 1 2 3 4int i = 0;
while (true) {
if (i == 5) {
break;
}
cout << "i = " << i << endl;
i++;
}
// outputs: 0 1 2 3 4continue statement
The continue statement is used to skip the rest of the code block inside the loop and continue the loop.
- In
whileordo-whileloop, the next iteration starts after the condition is evaluated. - In
forloop, the increment part is executed first, then the condition is evaluated.
for (int i = 0; i < 10; i++) {
if (i == 5) {
continue;
}
cout << "i = " << i << endl;
}
// 6 is output directly because the continue statement is executed when i == 5.
// outputs: 0 1 2 3 4 6 7 8 9Example:
int i = 0;
while (i < 10) {
if (i == 5) {
continue;
}
cout << "i = " << i << endl;
i++;
}
// outputs: 0 1 2 3 4 then endless loopint i = 0;
while (i < 10) {
cout << "i = " << i << endl;
i++;
if (i == 5) {
continue;
}
}
// outputs: 0 1 2 3 4 6 7 8 9goto 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 somethingLabels 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)
{
cerr << "The input is out of range." << endl;
goto EXIT_ERROR;
}
result = value * value;
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++.