Default Arguments
Default arguments in C++ allow you to specify a default value for a function parameter. If a value is not provided for that parameter when the function is called, the default value is used.
Syntax:
return_type function_name(parameter_type param1 = default_value, parameter_type param2 = default_value, ...) {
// Function body
}
Example:
#include <iostream>
using namespace std;
void greet(string name = "World") {
cout << "Hello, " << name << "!" << endl;
}
int main() {
greet(); // Uses the default argument
greet("Alice");
return 0;
}
Output:
Hello, World!
Hello, Alice!
Const Arguments
const arguments in C++ are used to indicate that a function parameter should not be modified within the function. This helps prevent accidental modifications and improves code safety.
Syntax:
return_type function_name(const parameter_type& param) {
// Function body
}
Example:
#include <iostream>
using namespace std;
void display(const string& message) {
cout << message << endl;
}
int main() {
string greeting = "Hello";
display(greeting);
return 0;
}
Output:
Hello
Combining Default Arguments and const Arguments
You can combine default arguments and const arguments to create more flexible and safer functions.
Example:
void printArray(const int arr[], int size = 0) {
for (int i = 0; i < size; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
This function takes an array and its size as arguments. The size parameter has a default value of 0, allowing the function to be called with or without specifying the size. The const keyword ensures that the array is not modified within the function.
Key Points:
Default arguments provide flexibility in function calls.
const arguments help prevent accidental modifications to parameters.
You can combine default arguments and const arguments to create more powerful functions.
תגובות