0
0
CppHow-ToBeginner · 3 min read

How to Use Default Arguments in C++: Syntax and Examples

In C++, you can specify default arguments in function declarations by assigning values to parameters. These default values are used when the caller omits those arguments, allowing flexible function calls.
📐

Syntax

Default arguments are set by assigning a value to a function parameter in its declaration. If the caller does not provide that argument, the default value is used.

  • Parameter with default: type name = default_value
  • Default values must be specified from right to left. You cannot skip a parameter in the middle.
  • Defaults are usually given in function declarations, not definitions.
cpp
void greet(std::string name = "Guest", int age = 0);
💻

Example

This example shows a function greet with default arguments. You can call it with zero, one, or two arguments. The missing arguments use their default values.

cpp
#include <iostream>
#include <string>

void greet(std::string name = "Guest", int age = 0) {
    std::cout << "Hello, " << name;
    if (age > 0) {
        std::cout << ", age " << age;
    }
    std::cout << "!" << std::endl;
}

int main() {
    greet();                // Uses both defaults
    greet("Alice");       // Uses default age
    greet("Bob", 30);     // Uses no defaults
    return 0;
}
Output
Hello, Guest! Hello, Alice! Hello, Bob, age 30!
⚠️

Common Pitfalls

Some common mistakes when using default arguments:

  • Defining default values in both declaration and definition causes errors. Put defaults only once, usually in the declaration.
  • Default arguments must be trailing. You cannot have a default argument followed by a non-default argument.
  • Overloading functions with default arguments can cause ambiguity.
cpp
/* Wrong: default in both declaration and definition */
void foo(int x = 5); // declaration
void foo(int x = 10) { // definition - error
    // ...
}

/* Correct: default only in declaration */
void foo(int x = 5); // declaration
void foo(int x) { // definition
    // ...
}
📊

Quick Reference

RuleDescription
Default arguments go from right to leftYou cannot skip parameters in the middle.
Specify defaults only oncePut default values in function declarations, not definitions.
Callers can omit trailing argumentsMissing arguments use default values automatically.
Avoid ambiguity with overloadsMixing overloads and defaults can confuse the compiler.

Key Takeaways

Specify default arguments by assigning values in function declarations.
Default arguments must be trailing parameters from right to left.
Provide default values only once to avoid compilation errors.
Call functions with fewer arguments to use defaults automatically.
Be careful mixing default arguments with function overloading.