C++ Functions Parameters
Parameters and Arguments
Information can be passed to functions as a parameter. Parameters act as variables inside the function.
Parameters are specified after the method name, inside the parentheses. You can add as many parameters as you want, just separate them with a comma:
Syntax
void functionName(parameter1, parameter2, parameter3) {
// code to be executed
}
The following example has a
function that takes a string
called fname as parameter.
When the function is called, we pass along a first name,
which is used inside the function to print the full name:
Example
void myFunction(string fname) {
cout << fname << " Refsnes\n";
}
int main() {
myFunction("Liam");
myFunction("Jenny");
myFunction("Anja");
return 0;
}
// Liam Refsnes
// Jenny Refsnes
//
Anja Refsnes
Run example »
When a parameter is passed to the function, it is called an argument. So, from the example above: string fname
is a parameter, while Liam
, Jenny
and Anja
are arguments.
Multiple Parameters
You can add as many parameters as you want:
Example
void myFunction(string fname, int age) {
cout << fname << " Refsnes.
" << age << " years old. \n";
}
int main() {
myFunction("Liam", 3);
myFunction("Jenny", 14);
myFunction("Anja", 30);
return 0;
}
// Liam Refsnes. 3 years old.
// Jenny Refsnes. 14 years old.
// Anja Refsnes. 30 years old.
Run example »
Note that when you are working with multiple parameters, the function call must have the same number of arguments as there are parameters, and the arguments must be passed in the same order.
Return Values
The void
keyword, used in the examples above, indicates that the
function should not return a value. If you
want the function to return a value, you can use a data type (such as int
,
string
, etc.) instead of void
, and use the return
keyword inside the function:
Example
int myFunction(int x) {
return 5
+ x;
}
int main() {
cout << myFunction(3);
return 0;
}
// Outputs
8 (5 + 3)
Run example »
This example returns the sum of a function with two parameters:
Example
int myFunction(int x, int y) {
return x + y;
}
int main()
{
cout << myFunction(5, 3);
return 0;
}
// Outputs 8 (5 + 3)
Run example »
You can also store the result in a variable:
Example
int myFunction(int x, int y) {
return x + y;
}
int main() {
int z = myFunction(5, 3);
cout << z;
return 0;
}
// Outputs 8 (5 + 3)
Run example »