How to pass parameters and arguments to a function in C++
Overview
In C++, a parameter is a variable that is defined while creating a function. When a function is called, these variables either take or receive arguments. An argument in C++ is the value that is passed to a function whenever that specific function is called.
Furthermore, a parameter is specified inside a parenthesis () right
after the function name. We can add as many parameter values as we wish to inside a function.
Syntax
To pass a parameter and/or argument values to a function, we use the following syntax:
void nameOfFunction(parameter1, parameter2){// block of code to be executed}intmain(){ // calling the functionnameOfFunction(argument1, argument2);return 0;}
Code example
In the code below, we will create a function that takes a single parameter. Whenever we call the function, we pass an argument to the function.
#include <iostream>#include <string>using namespace std;void myFunction(string myname) {cout << myname << " Onyejiaku\n";}int main() {// calling the functionmyFunction("Theophilus");myFunction("Chidalu");return 0;}
Code explanation
- Line 5: We declare a function
myfunctionand pass a parametermynameto the function. - Line 6: We create a code block to be executed whenever the function is called.
- Line 10: We call the function, and this time it passes the argument
"Theophilus"to the function. - Line 11: We call the function again, and this time it passes the argument
"Chidalu"to the function.