C++ Functions Parameters C-PLUS-PLUS

C++ Functions Parameters  

C++ Functions Parameters

C++ Functions Parameters

Information can be passed to functions as a parameter. Parameters act as variables inside the function.

Syntax

void functionName(parameter1parameter2parameter3) {
  // code to be executed
}

Example

#include <iostream>
#include <string>
using namespace std;

void myFunction(string fname) {
  cout << fname << " Chahar\n";
}

int main() {
  myFunction("Deepak");
  myFunction("Miss Meenkashi");
  myFunction("Ajay");
  return 0;
}
 

Output:

Deepak Chahar

Miss Meenakshi Chahar

Ajay Chahar

When a parameter is passed to the function, it is called an argument. So, from the example above: fname is a parameter, while DeepakMiss Meenakshi and Ajay are arguments.

Default Parameter Value

You can also set a default parameter value, by using the equals sign (=). If we call the function without an argument, it uses the default value.

Example

#include <iostream>
#include <string>
using namespace std;

void myFunction(string country = "Canada") {
  cout << country << "\n";
}

int main() {
  myFunction("Rusia");
  myFunction("India");
  myFunction();
  myFunction("USA");
  return 0;
}
 

Output:

Rusia

India

Canada

USA

Multiple Parameters

You can add as many parameters as you want. Separate each with a comma ,

Example

#include <iostream>
#include <string>
using namespace std;

void myFunction(string fname, int age) {
  cout << fname << " Chahar. " << age << " years old. \n";
}

int main() {
  myFunction("Deepak", 22);
  myFunction("Miss Meenakshi", 24);
  myFunction("Ajay", 19);
  return 0;
}
 

Output:

Deepak Chahar. 22 years old.
Miss Meenakshi. 24 years old.
Ajay Chahar. 19 years old.

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries