Default Arguments

Parameters with default values

Interview Relevant: Function flexibility

Default Arguments

Default arguments allow omitting parameters when calling functions.

Rules

  • Default arguments must be rightmost parameters
  • Specify in declaration, not definition (if separate)
  • Cannot specify same default twice

Code Examples

Using default argument values.

cpp
1// Default arguments
2void greet(string name, string greeting = "Hello") {
3    cout << greeting << ", " << name << "!" << endl;
4}
5
6greet("Alice");           // Hello, Alice!
7greet("Bob", "Hi");       // Hi, Bob!
8
9// Multiple defaults
10void configure(int a, int b = 10, int c = 20) {
11    cout << a << " " << b << " " << c << endl;
12}
13
14configure(1);        // 1 10 20
15configure(1, 2);     // 1 2 20
16configure(1, 2, 3);  // 1 2 3

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In