What Are Default Arguments in C++?
Default arguments in C++ allow you to set default values for function parameters. If the caller doesn’t provide a value for a parameter, the function uses the default.
It’s like saying: “If nobody tells me what to use, I’ll use this value instead!” 😄
📘 Syntax of Default Arguments
return_type function_name(type param1, type param2 = default_value);
Let’s see how it works with an example!
🧪 Example: Function with One Default Argument
#include <iostream> using namespace std; void greet(string name = "Guest") { cout << "Hello, " << name << "!" << endl; } int main() { greet(); // Will use default argument greet("Alice"); // Will use provided argument return 0; }
🧪 Example: Multiple Default Arguments
You can also set defaults for multiple parameters, but they must go from right to left!
#include <iostream> using namespace std; void showInfo(string name, int age = 18, string city = "Unknown") { cout << "Name: " << name << ", Age: " << age << ", City: " << city << endl; } int main() { showInfo("Max"); showInfo("Lily", 22); showInfo("Jake", 30, "New York"); return 0; }
⚠️ Rules to Remember
- Default values must be provided from right to left.
- You can skip some arguments, but not the ones in between.
- Default arguments are usually declared in the function declaration.
✅ Summary
- Default arguments make your functions more flexible and easier to call.
- If a caller skips a parameter, the default value is used.
- Useful for setting optional behavior!
Try using default arguments to write smarter, cleaner, and more convenient functions! 💡