C++ Function Parameters
Information can be passed to functions through parameters. Parameters act like variables that are filled in when the function is called. The values you actually send in are called arguments. Parameters make a function flexible, because the same function can work on different data each time you call it.
Passing data into a function
A parameter is written inside the parentheses of a function, with a type and a name, just like a normal variable. When you call the function, you supply an argument for each parameter. Inside the function you can use the parameter exactly as if it were a local variable.
A function with one parameter
#include <iostream>
#include <string>
using namespace std;
void greet(string name) {
cout << "Hello, " << name << "!\n";
}
int main() {
greet("Priya");
greet("Sam");
return 0;
}
// Outputs:
// Hello, Priya!
// Hello, Sam!Multiple parameters
You can add as many parameters as you need, separated by commas. When you call the function, the arguments are matched to the parameters in the same order they are written, so the first argument fills the first parameter, the second fills the second, and so on.
Two parameters of different types
#include <iostream>
#include <string>
using namespace std;
void printAge(string name, int age) {
cout << name << " is " << age << " years old.\n";
}
int main() {
printAge("Aisha", 20);
printAge("Leo", 35);
return 0;
}
// Outputs:
// Aisha is 20 years old.
// Leo is 35 years old.Default parameter values
You can give a parameter a default value using the = sign. If a caller leaves out that argument, the default is used automatically. Default values must be the last parameters in the list, so any parameters without a default come first.
Using a default value
#include <iostream>
#include <string>
using namespace std;
void greet(string name, string greeting = "Hello") {
cout << greeting << ", " << name << "!\n";
}
int main() {
greet("Maria"); // Uses the default "Hello"
greet("Ken", "Welcome"); // Overrides the default
return 0;
}
// Outputs:
// Hello, Maria!
// Welcome, Ken!