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
breakafter eachcase, 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
defaultlabel for robustness. - If the
defaultbranch 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
doblock. - 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: Disablesassertchecks when defined.- Common predefined macros:
__FILE__ // Current source file name
__LINE__ // Current line number
__DATE__ // Compilation date
__TIME__ // Compilation time
- The
assertmacro verifies assumptions during debugging:
#include <cassert>
assert(condition); // Program aborts if condition is false (unless NDEBUG is defined)