Default Function Arguments

🟢 Beginner

📖 Definition

Default parameters allow function callers to omit trailing arguments. Default values must be specified starting from the rightmost parameter in the prototype signature.

💡 Code Example

#include <iostream>

void displayMessage(const std::string& msg, int repeat = 1) {
    for (int i = 0; i < repeat; ++i) {
        std::cout << msg << "\n";
    }
}

int main() {
    displayMessage("Hello C++!"); // Uses default repeat = 1
    displayMessage("Repeating...", 2);
    return 0;
}