C++ Function Parameters
In C++, function parameters are variables declared in the function declaration and definition. They allow you to pass data into functions and specify what type of data a function can accept when it is called. Parameters are optional and can be of various types, including built-in types, user-defined types, pointers, and references.
1. Passing Parameters by Value
Example of passing parameters by value:
#include <iostream>
// Function declaration
void display(int num);
int main() {
int x = 5;
// Function call with argument
display(x);
return 0;
}
// Function definition
void display(int num) {
std::cout << "Value received: " << num << std::endl;
}
2. Passing Parameters by Reference
Example of passing parameters by reference:
#include <iostream>
// Function declaration
void increment(int &num);
int main() {
int x = 5;
// Function call with argument passed by reference
increment(x);
// Output the modified value of x
std::cout << "Incremented value: " << x << std::endl;
return 0;
}
// Function definition
void increment(int &num) {
num++;
}
3. Default Parameters
Example of using default parameters:
#include <iostream>
// Function declaration with default parameter
void greet(std::string name = "Guest");
int main() {
// Function calls with and without argument
greet("Alice");
greet();
return 0;
}
// Function definition
void greet(std::string name) {
std::cout << "Hello, " << name << "!" << std::endl;
}
4. Function Overloading with Parameters
Example of function overloading with different parameter types:
#include <iostream>
// Function declarations
void display(int num);
void display(double num);
int main() {
int x = 5;
double y = 3.14;
// Function calls with different arguments
display(x);
display(y);
return 0;
}
// Function definitions
void display(int num) {
std::cout << "Integer value: " << num << std::endl;
}
void display(double num) {
std::cout << "Double value: " << num << std::endl;
}
Conclusion
Function parameters in C++ enable you to pass data into functions, providing flexibility and reusability in your code. This chapter covered passing parameters by value and reference, using default parameters, and function overloading with different parameter types. Understanding function parameters allows you to design modular and efficient C++ programs by tailoring function behavior to specific needs and scenarios.