Loops
while loop
- repeat the code until expression evaluates to true
- unless
break is used to immediately get out of the loop
- unless
continue is used to return to the top and reevaluate the expression
int i { 0 };
while (i < 5) {
cout << "Hello World" << endl;
++i;
}
do/while loop
- code execution comes first, then evaluates expression to guarantee at least one code execution
int i { 100 };
do {
cout << "Hello World" << endl;
++i;
} while (i < 5);
for loop
- can be converted into
while loop and vice versa
for (starting expression; end condition; statement to execute at the end){}
Range-based for loop
- used for easy iteration over elements in a container (e.g. C-style array, initializer lists, any type that has
begin() and end() like array, vector
array arr { 1, 2, 3, 4 };
for (int i : arr) { cout << i << endl; }
- from C++20, we can use initializers with range-based
for loop, similar to initializers in if and switch
for (array arr { 1, 2, 3, 4 }; int i: arr) { cout << i << endl; }
Initializer Lists
- defined in
<initializer_list> - make it easy to write functions that accept a variable number of arguments
- class template - specify types of elements in the lists in
<>
#include <initializer_list>
#include <iostream>
using namespace std;
int makeSum(initializer_list<int> values) {
int total { 0 };
for (int value : values) {
total += value;
}
return total;
}
int a { makeSum({ 1, 2, 3 }) };
int b { makeSum({ 10, 20, 30, 40, 50, 60 }) };
- type-safe, so all elements in the list has to be of the same type