• Home
  • 6.8 Default Arguments

6.8 Default Arguments

View Categories

6.8 Default Arguments

1 min read

Table of Contents

Default arguments allow a function parameter to have a predefined value that is used when the caller does not provide a corresponding argument. They make it possible to call the same function with different numbers of arguments while maintaining a single function definition.

A default argument is specified in the function declaration or definition by assigning a value to the parameter. Once a default value is provided, subsequent parameters in the same parameter list must also have default values.

Source Code #

#include <iostream>

void greet(std::string name = "User")
{
    std::cout << "Hello, " << name << "!\n";
}

int main()
{
    greet();
    greet("Alice");

    return 0;
}

Output #

Hello, User!
Hello, Alice!

Explanation #

  • name = "User" specifies "User" as the default argument for the name parameter.
  • greet() is called without an argument, so the default value "User" is used.
  • greet("Alice") provides an argument explicitly, so "Alice" replaces the default value.
  • Default arguments are used only when the corresponding argument is omitted from the function call.
  • Default arguments are specified using the assignment operator (=) in the parameter list.
  • Once a parameter has a default argument, parameters appearing after it must also have default arguments.
  • Default arguments can reduce the number of overloaded functions required for cases where parameters have common default values.
  • return 0; terminates the program successfully.

Powered by BetterDocs

Leave a Reply

Your email address will not be published. Required fields are marked *