Default parameters
- C++ course
- Beginner
- Lesson 69/116
- 5 min
Learn to define parameters with default values.
Default parameters
You can give a parameter a default value; if the call skips it, the default is used. In void greet(std::string name = "guest") the default of name is "guest". The call greet() is the same as greet("guest").
The default is written once in the definition; if the declaration and definition are separate, the default goes only on the declaration. Key habit: default parameters must come after non-default ones. void f(int a, int b = 0) is valid, void f(int b = 0, int a) is not.
Which parameter gets a default?
The order of default parameters matters. void f(int a, int b = 0, int c = 0) is valid: defaults at the end. void f(int a = 0, int b, int c = 0) is invalid because b has no default while a parameter after it does.
The logic is that arguments bind left to right at the call. When you skip one parameter, you must skip every parameter to its right. That is why defaults cluster at the end. Putting optional parameters last makes life easier for both the compiler and the reader.
Practice Write greet with a default parameter
Define void greet(std::string name = "guest") whose body is std::cout << "hi " << name << std::endl;. In main, first call greet(), then greet("Alex").
Starter code
#include <iostream>
#include <string>
// Define greet with a default parameter
int main() {
// greet calls (one without, one with argument)
return 0;
}Sample solution
#include <iostream>
#include <string>
void greet(std::string name = "guest") {
std::cout << "hi " << name << std::endl;
}
int main() {
greet();
greet("Alex");
return 0;
}Expected output
hi guest hi Alex
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match default parameter behavior
| Term | Meaning |
|---|---|
greet() |
Call with default |
greet("Alex") |
Call with argument |
name = "guest" |
Default value |
int a, int b = 0 |
Valid order |
2 For void f(int a, int b = 0), what is b in the call f(5)?
void f(int a, int b = 0);
f(5);- 5
- 0 Correct answer
- Undefined
- Compile error
Explanation: when b is skipped, the default 0 is used.
3 Complete the default value
void greet(std::string name ____ "guest") { std::cout << name; }
void greet(std::string name = "guest") { std::cout << name; }
Explanation: = gives the default value.