Welcome to CodeYourCraft's guide on C++ Default Arguments! Today, we'll explore how to provide default values for function arguments, making your code more flexible and easier to manage. Let's get started!
Default arguments are values that are automatically assigned to a function parameter when no argument is provided during function call. This feature allows you to create more versatile and user-friendly functions.
To define a default argument for a function, simply assign a value to the function parameter within the function definition. When you call the function without providing an argument for that specific parameter, the default value will be used.
Here's a simple example:
#include <iostream>
void greet(const std::string& name = "Guest") {
std::cout << "Hello, " << name << "!\n";
}
int main() {
greet("John"); // Output: Hello, John!
greet(); // Output: Hello, Guest!
return 0;
}In this example, the function greet() accepts a string parameter named name, with a default value of "Guest". When we call greet("John"), we pass our own value for name. However, when we call greet() without providing an argument, the default value "Guest" is used instead.
Default arguments can be very useful in real-world projects, such as:
#include <iostream>
void printMessage(const std::string& message = "Welcome to CodeYourCraft!", int times = 1) {
for(int i = 0; i < times; ++i) {
std::cout << message << "\n";
}
}
int main() {
printMessage(); // Output: Welcome to CodeYourCraft! (once)
printMessage(3); // Output: Welcome to CodeYourCraft! (three times)
return 0;
}In this example, we've created a printMessage() function that accepts two parameters: message and times. By default, the function will print the welcome message once. However, if we call the function with an argument for times, it will print the message that many times.
What is the purpose of default arguments in C++?
We hope this guide has given you a solid understanding of C++ Default Arguments. Happy coding! šš