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
| Rule | Description |
|---|---|
| Default arguments go from right to left | You cannot skip parameters in the middle. |
| Specify defaults only once | Put default values in function declarations, not definitions. |
| Callers can omit trailing arguments | Missing arguments use default values automatically. |
| Avoid ambiguity with overloads | Mixing 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.