Function Parameters
Data can be passed to a function as a parameter. These are variables inside of functions. These are specified withing the brackets with their datatypes.
Syntax:
void function( datatype variable; datatype variable;)
{
//code block
}
In the following example Honey is an argument , however name is a parameter
Example:
#include <iostream>
#include <string>
using namespace std;
void function(string name)
{
cout << name << " surname\n";
}
int main()
{
myFunction("Honey");
myFunction("sam");
myFunction("Anja");
return 0;
}
Output:
Honey surname
sam surname
Anja surname
Return Values
In the following example the keyword return is used. Using int instead of void helps us to derive a return value. However as discussed earlier void doesn't return a value.
Example:
#include <iostream>
using namespace std;
int myFunction(int x, int y)
{
return x + y;
}
int main()
{
int z = myFunction(2, 3);
cout << z;
return 0;
}
Output
5
Call by Reference
You can also pass a reference to the function by using pointers of such as in the following example:
#include <iostream>
using namespace std;
void swapNums(int &x, int &y) {
int z = x;
x = y;
y = z;
}
int main() {
int firstNum = 10;
int secondNum = 20;
cout << "Before swap: " << "\n";
cout << firstNum << secondNum << "\n";
swapNums(firstNum, secondNum);
cout << "After swap: " << "\n";
cout << firstNum << secondNum << "\n";
return 0;
}
Output:
Before swap:
1020
After swap:
2010