cpp / beginner
Snippet
Default Parameters: Simplifying Function Calls
Default parameters allow functions to be called with fewer arguments. The default values are used when arguments are omitted. Default parameters must be at the end of the parameter list. They make APIs simpler while maintaining flexibility.
snippet.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>#include <string>void greet(std::string name, std::string prefix = "Hello", int times = 1) {for (int i = 0; i < times; i++) {std::cout << prefix << ", " << name << "!" << std::endl;}}int main() {greet("World");greet("Alice", "Hi");greet("Bob", "Hey", 3);return 0;}
Breakdown
1
void greet(..., std::string prefix = "Hello", ...)
Default value "Hello" used when prefix is not provided
2
greet("World");
Uses default prefix "Hello" and default times 1
3
greet("Alice", "Hi");
Uses "Hi" as prefix, default times 1
4
greet("Bob", "Hey", 3);
All arguments provided, no defaults used