Lesson 94 +10 XP

Default Parameters

Default Parameters

Sometimes an argument is optional. C++ lets a parameter have a default value that gets used whenever the caller omits it.

Setting a default

Add = value right in the parameter list:

void myFunction(string country = "Norway") {
  cout << country;
}
  • The parameter country has the default value "Norway".
  • Defaults are written like parameter = default_value in the parameter list.

The call decides

If you pass an argument, it overrides the default. If you don't, the default applies:

myFunction("Sweden");   // prints "Sweden"
myFunction();           // prints "Norway"
myFunction("India");    // prints "India"
  • With an argument, the default is ignored.
  • With no argument, the default value is used.

Keep defaults at the end

A parameter with a default must come after any parameter without one so the calls stay unambiguous:

void greet(string name, string greeting = "Hello") { }  // good
void bad(bool flag = true, int n) { }     // invalid: default not at the end

TL;DR

  • A default parameter uses =: void f(int x = 5).
  • If the caller passes a value, it wins; if not, the default applies.
  • Place defaulted parameters after the non-defaulted ones.
  • Defaults make the function easier to call.