C++ Functions Parameters C-PLUS-PLUS
- C++ Introduction
- C++ Syntax
- C++ Output (cout <<)
- C++ Comments
- C++ Variables
- C++ User Input
- C++ Data Types
- C++ Operators
- C++ Strings
- C++ Math
- C++ Booleans
- C++ If Else
- C++ Switch
- C++ While Loop
- C++ Do/While Loop
- C++ For Loop
- C++ Break and Continue
- C++ Arrays
- C++ References
- C++ Pointers
- C++ Functions
- C++ Functions Parameters
- C++ Function Overloading
- C++ OOP
- C++ Classes and Objects
- C++ Class Methods
- C++ Constructors
- Destructors in C++
- C++ Access Specifiers
- C++ Encapsulation
- C++ Inheritance
- C++ Polymorphism
- C++ Files
- C++ Exception Handling
C++ Functions Parameters
C++ Functions Parameters
Information can be passed to functions as a parameter. Parameters act as variables inside the function.
Syntax
// 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 Deepak
, Miss 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.