C++ Control Flow and Preprocessor Essentials

Empty Statement

An empty statement consists solely of a semicolon (;). It is typically used when the loop’s condition itself performs all necessary work:

while (std::cin >> input && input != target) {
    ; // Reads from input until a specific value is encountered
}

Switch Statement

Case Labels

  • Always include a break after each case, even the last one, to prevent fall-through.
  • Case labels need not start on a new line.
  • Labels must be followed by integral constant expressions:
// case 3.14:   // Invalid — not an integer
// case var:    // Invalid — not a constant
  • Duplicate case values cause compilation errors.

Default Label

  • Include a default label for robustness.
  • If the default branch performs no action, it must contain at least a empty statement (;).

Variable Definitions Inside Switch

Variables defined within a case must be enclosed in a block {} to ensure proper scope and initialization:

case true: {
    std::string filename = generate_name();
    // use filename
    break;
}
case false:
    // ...
    break;

While Loop Example

Copying data from a source to a destination:

while (*source) {
    *dest++ = *source++;
}

Always ensure loops terminate—use break or return where appropriate to avoid infinite execution.

Do-While Loop

do {
    // loop body
} while (condition);
  • Ends witth a semicolon.
  • Variables referenced in the condiiton must be declared before the do block.
  • Variables declared inside the loop body are not visible in the condition.

Example:

std::string response;
do {
    int x, y;
    std::cout << "Enter two numbers: ";
    std::cin >> x >> y;
    std::cout << "Sum: " << x + y << "\nContinue? (YES/NO): ";
    std::cin >> response;
} while (!response.empty() && response[0] != 'N');

Break Statement

The break statement exits the nearest enclosing loop (for, while, do-while) or switch. It cannot be used outside these contexts.

Preprocessor Features

  • NDEBUG: Disables assert checks when defined.
  • Common predefined macros:
__FILE__  // Current source file name
__LINE__  // Current line number
__DATE__  // Compilation date
__TIME__  // Compilation time
  • The assert macro verifies assumptions during debugging:
#include <cassert>
assert(condition); // Program aborts if condition is false (unless NDEBUG is defined)

Tags: C++ Control Flow preprocessor switch loops

Posted on Mon, 06 Jul 2026 16:42:57 +0000 by holiks