Programming Tutorials

Default arguments in C++

By: Babbar Ankit in C++ Tutorials on 2009-05-30  

In C++, default arguments allow a function to be called with fewer arguments than declared. The missing arguments are replaced with the default values. This can be useful when a function has a parameter that is commonly used with a specific value.

Here is an example of a function with a default argument:

void printMessage(std::string message, int times = 1) {
    for (int i = 0; i < times; i++) {
        std::cout << message << std::endl;
    }
}

In this example, the printMessage function takes a string argument message and an integer argument times, which has a default value of 1. This means that if times is not provided when the function is called, it will default to 1.

For example, we can call the function like this:

printMessage("Hello"); // prints "Hello" once
printMessage("World", 3); // prints "World" three times

In the first call, the function is called with only one argument, so the default value of 1 is used for the times parameter. In the second call, the function is called with two arguments, so the second argument is used for the times parameter.






Add Comment

* Required information
1000

Comments

No comments yet. Be the first!

Most Viewed Articles (in C++ )

Latest Articles (in C++)