Functions Parameters
C++ Function Parameters
In C++, function parameters are variables used to pass values from the calling code to the function. These parameters allow functions to operate on specific data, making them more versatile and reusable. Function parameters are defined in the function prototype and function definition, specifying the type and name of each parameter.
1. Function Declaration/Prototype:
// Function declaration with parameters
void printMessage(std::string message, int times);
In this example, the printMessage function is declared to take two parameters: a std::string named message and an int named times. This function declaration is often placed at the beginning of the program or in a header file.
2. Function Definition:
// Function definition with parameters
void printMessage(std::string message, int times) {
for (int i = 0; i < times; ++i) {
std::cout << message << std::endl;
}
}
In the function definition, the parameters are repeated, and their types must match those specified in the declaration. The function body then uses these parameters as local variables.
3. Function Call:
int main() {
// Function call with arguments
printMessage("Hello, World!", 3);
return 0;
}
When calling the printMessage function, you provide arguments for each parameter. In this case, the message is "Hello, World!", and it will be printed three times.
Default Parameter Values:
// Function declaration with default parameter values
void printMessage(std::string message = "Default Message", int times = 1);
In this case, if you call printMessage() without arguments, it will use the default values. If you provide arguments, those values will be used.
Function Overloading:
// Function overloading
void printMessage(std::string message);
void printMessage(int value);
In this example, there are two printMessage functions with different parameter types. The appropriate function is selected based on the argument types during the function call.
Reference Parameters:
// Function with reference parameters
void increment(int& x) {
x++;
}
int main() {
int number = 5;
// Function call with reference parameter
increment(number);
std::cout << "Incremented value: " << number << std::endl;
return 0;
}
In this case, increment takes an int& reference parameter, and changes made to x inside the function affect the original number variable.
Understanding function parameters and their variations is essential for writing flexible and modular C++ code. Whether using default values, overloading, or references, proper use of parameters enhances the reusability and clarity of your functions.