Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

function
arguments
parameter
c++
communitycreator

How to pass parameters and arguments to a function in C++

Onyejiaku Theophilus Chidalu

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 function
  nameOfFunction(argument1, argument2);
  return 0;
}
Function syntax

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 function
  myFunction("Theophilus");
  myFunction("Chidalu");
  return 0;
}
Passing a parameter and an argument to a function

Code explanation

  • Line 5: We declare a function myfunction and pass a parameter myname to 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.

RELATED TAGS

function
arguments
parameter
c++
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring