Function Parameters and Arguments
Introduction
In the world of programming, functions are reusable pieces of code that perform specific tasks. When defining a function, we may want to pass some data to it and this data is known as parameters. When we call the function, we provide this data, and these are known as arguments. In this tutorial, we will be discussing function parameters and arguments in C++.
What are Function Parameters?
Function parameters are the inputs to a function. These are the variables that a function uses to compute the result. When defining a function, we specify the parameters in the function declaration. Let's look at an example:
void printMessage(string message) {
cout << message << endl;
}
In the above example, message
is the parameter of the function printMessage
. The parameter message
is of type string
.
What are Function Arguments?
Function arguments are the actual values that are passed to the function when it is called. These values are used to replace the function parameters. Let's look at an example:
printMessage("Hello, World!");
In the above example, "Hello, World!" is the argument which is passed to the function printMessage
.
Types of Function Parameters
C++ supports three types of function parameters:
Pass by Value: In this method, the value of the argument is copied into the function’s parameter. Any changes made to the parameter do not affect the argument.
void changeValue(int value) {
value = 100;
}Pass by Reference: In this method, a reference to the argument is copied into the function’s parameter. Hence, any changes made to the parameter affect the argument.
void changeValue(int &value) {
value = 100;
}Pass by Address: In this method, the address of the argument is copied into the function’s parameter. Hence, any changes made to the parameter affect the argument.
void changeValue(int *value) {
*value = 100;
}
Default Arguments
C++ allows us to specify default values for parameters. If a parameter is given a default value, it becomes optional when the function is called. If an argument is provided for this parameter, it will override the default value.
void printMessage(string message = "Hello, World!") {
cout << message << endl;
}
In the above example, if printMessage
is called without any arguments, it will print "Hello, World!".
Conclusion
Understanding function parameters and arguments is crucial to mastering C++. They allow us to write flexible and reusable code. Always remember the difference between parameters and arguments: parameters are used in the function definition, while arguments are the actual values passed into the function.