C++ Default Function Arguments: How They Work & Best Practices
C++ Default Function Arguments
Explore how to assign default values to function parameters in C++, with step‑by‑step examples and practical guidelines.
In C++, function parameters can be given default values. When a call omits an argument, the compiler substitutes the default. If an argument is supplied, the default is ignored.
How Default Arguments Work

Consider the following illustration:
temp()uses both defaults.temp(6)overrides the first parameter; the second remains default.temp(6, -2.3)provides values for both, overriding both defaults.- Calling
temp(3.4)mistakenly passes a double to an int parameter. The compiler truncates the value to3, demonstrating that argument types must match the declaration order.
Example: Using Default Arguments
#include <iostream>
using namespace std;
// Prototype with default arguments
void display(char = '*', int = 3);
int main() {
int count = 5;
cout << "No argument passed: ";
display(); // uses '*', 3
cout << "First argument passed: ";
display('#'); // uses '#', 3
cout << "Both arguments passed: ";
display('$', count); // uses '$', 5
return 0;
}
void display(char c, int count) {
for(int i = 1; i <= count; ++i) {
cout << c;
}
cout << endl;
}
Output
No argument passed: *** First argument passed: ### Both arguments passed: $$$$$
The program behaves as follows:
display()uses the defaultsc='*'andcount=3.display('#')overrides only the first argument; the second remains default.- When both arguments are supplied, defaults are ignored.
Defining defaults directly in the function definition is also valid and often clearer:
#include <iostream>
using namespace std;
void display(char c = '*', int count = 3) {
for(int i = 1; i <= count; ++i) {
cout << c;
}
cout << endl;
}
int main() {
int count = 5;
cout << "No argument passed: ";
display();
cout << "First argument passed: ";
display('#');
cout << "Both arguments passed: ";
display('$', count);
return 0;
}
Key Points to Remember
- After a parameter receives a default value, every following parameter must also have a default. For example:
// Invalid void add(int a, int b = 3, int c, int d); // Valid void add(int a, int c, int b = 3, int d = 4); - When defaults are specified in the definition rather than the prototype, the definition must precede any call. Otherwise the compiler will issue an error.
C Language
- Mastering C++ Operators: A Complete Guide with Practical Examples
- C++ Function Overloading: A Practical Guide
- How to Pass Arrays to Functions in C++: A Practical Guide
- Four Proven Patterns for User‑Defined Functions in C
- C++ Programming Basics: What Is C++ and Why It Matters
- Top 15 C++ Online Courses to Master the Language (2024 Update)
- Function Pointers in C: Practical Examples and Best Practices
- Mastering Variable Arguments in C: A Practical Guide
- Master C++ Web Programming with CGI
- Fanuc Decimal Point Programming: Overview & Parameter Settings