Control flow in C++ will look familiar from any C-family language. The details worth knowing are the ones that differ.
Conditionals are if, else if and else. The condition is contextually converted to bool, which means any non-zero number is true - a source of bugs when somebody writes if (x = 5) meaning ==, assigning 5 and then treating it as true. Compile with -Wall and the compiler asks whether you meant that. C++17 added an init-statement: if (auto it = m.find(key); it != m.end()) declares it, tests it, and scopes it to the if and its else. Use it - a variable that exists only where it is meaningful is a variable you cannot misuse later.
switch tests one integral or enum value against constant cases. Two rules bite. Cases fall through unless you break - deliberate fall-through is legal and occasionally useful, and since C++17 you can mark it [[fallthrough]]; so both the compiler and the next reader know you meant it. And you cannot declare a variable inside a case without braces, because the other cases are in the same scope.
Loops come in three classic forms plus one modern one. while tests first and may run zero times. do-while tests last and always runs at least once - rare, and right for input validation. for puts initialization, condition and increment on one line, which keeps the loop's whole contract visible.
The one you will use most is the range-based for, added in C++11: for (const auto& item : container). It reads better, and more importantly it cannot get the bounds wrong, which is the single most common loop bug. Note the const auto& - by value you copy every element, which for a container of strings is a copy per iteration for no reason.
break leaves the innermost loop or switch; continue skips to the next iteration. Both are fine in moderation. A break out of a search loop is clearer than a flag variable tested in the condition. Several breaks and a continue in one loop usually means the loop is doing two jobs.
#include <iostream>
#include <vector>
#include <string>
int main()
{
int score{72};
// --- if / else if / else ---
if (score >= 90) { std::cout << "A\n"; }
else if (score >= 70) { std::cout << "B\n"; }
else { std::cout << "C\n"; }
// C++17 init-statement: declare, test, and scope it to the if.
std::vector<int> v{1, 2, 3};
if (auto size = v.size(); size > 2) {
std::cout << "has " << size << " items\n";
} // size does not exist past here, which is the point
// --- switch ---
char grade{'B'};
switch (grade) {
case 'A':
case 'B': // deliberate: A and B share a body
std::cout << "Pass\n";
break;
case 'C':
std::cout << "Marginal\n";
[[fallthrough]]; // C++17: I meant this
case 'D':
std::cout << "Review\n";
break;
default: {
int unknown{0}; // braces: a case needs its own scope
std::cout << "Unknown " << unknown << '\n';
break;
}
}
// --- the three classic loops ---
for (int i = 0; i < 3; ++i) { // ++i, not i++ - see below
std::cout << i << ' ';
}
std::cout << '\n';
int n{3};
while (n > 0) { std::cout << n-- << ' '; }
std::cout << '\n';
int attempts{0};
do { // always runs at least once
++attempts;
} while (attempts < 1);
// --- range-based for: prefer this ---
std::vector<std::string> names{"ada", "grace", "alan"};
for (const auto& name : names) { // const auto& - no copy per item
std::cout << name << ' ';
}
std::cout << '\n';
for (auto& name : names) { // auto& when you intend to modify
name += "!";
}
// --- break and continue, used where they read well ---
for (const auto& name : names) {
if (name.empty()) { continue; } // skip, do not nest
if (name[0] == 'g') {
std::cout << "found " << name << '\n';
break; // stop: we have what we came for
}
}
return 0;
}
/* Why ++i rather than i++ in a loop:
i++ must return the value BEFORE the increment, so conceptually it
copies first. For an int the compiler erases the difference. For an
iterator over a container it may not, and the habit costs nothing. */
Discussion
No questions on this topic yet. Sign in to ask the first one.