C++ control flow mirrors Java: if, else, for, while, do-while, and switch. Modern C++ adds range-based for over containers.
Range-based for
std::vector<int> nums = {1, 2, 3};
for (int n : nums) {
std::cout << n << " ";
}
switch
switch works on integral and enum types. Use break to avoid fall-through unless intentional.
Important interview questions and answers
- Q: Range-for requirements?
A: The type needsbegin()andend()in scope—works with arrays, vectors, strings, and more. - Q: switch on strings?
A: Not directly in older standards—use if/else chain orstd::map/hash map for dispatch.
Self-check
- How does do-while differ from while?
- Why prefer range-for over index loops when possible?
Tip: Range-based for works like enhanced for-loops in Java—prefer it over manual index loops when you do not need the index.
Interview prep
- Range-for requirements?
The type needs accessible
beginandend—works with arrays, vectors, strings, and custom types.- switch fall-through?
Missing
breakexecutes subsequent cases—document intentional fall-through with comments.