Function Parameters
I. In-Class Exercises
Programming Exercises
- Swap Two Numbers: L2091
- Remove Zeros from an Array: L2092
- Maximum and Minimum: L2093
- Comparing Arrays: L2094
II. Knowledge Summary
✨ Core Concept of Function Parameters
A function's parameters are the detailed information the function can receive, written inside the parentheses after the function name. Through parameters, callers can pass data to the function, and the function performs operations based on that data.
Formal Parameters
Parameters in a function declaration and definition are called formal parameters (or simply parameters). Formal parameters represent a category — what kind of information the function can accept. Like other local variables inside a function, formal parameters are created when entering the function and destroyed when exiting it.
Actual Arguments
If a function is defined with parameters, you must pass the required arguments when calling it. Since these values determine the actual computation result, the values passed during a function call are called actual arguments (or simply arguments).
This process can be understood as: assigning the values of actual arguments to formal parameters, then using the formal parameters for computation.
Format Example
The following code shows the correspondence between formal parameters and actual arguments in function declaration, call, and definition:
1// Function declaration
2void function_name(param1_type formal_param1, param2_type formal_param2);
3
4
5int main() {
6 // Call within main function
7 function_name(actual_arg1, actual_arg2);
8 return 0;
9}
10
11
12// Function definition
13void function_name(param1_type formal_param1, param2_type formal_param2) {
14 code inside function
15}✨ Parameter Passing Methods
In C++, there are two basic ways to pass parameters: pass by value and pass by reference. The key difference is whether modifications inside the function affect the original actual arguments.
Pass by Value
Pass by value means copying the value of the actual argument and passing the copy to the function parameter. Modifications to the parameter inside the function do not affect the original actual argument.
Advantages:
- Simple and easy to understand
- Does not change the actual argument's value
Disadvantages:
- The copy operation may incur performance overhead, especially for large objects
1void foo(int x) {
2 x = 20;
3}
4
5int main() {
6 int a = 10;
7 foo(a);
8 // The value of a is still 10
9 return 0;
10}Pass by Reference
Pass by reference means passing a reference to the actual argument to the function parameter. Modifications to the parameter inside the function directly affect the actual argument. Pass by reference uses the & symbol after the parameter type.
Advantages:
- No copy overhead, suitable for passing large objects
- The function can directly modify the actual argument
Disadvantages:
- Be careful about side effects from references — original data may be accidentally modified
1void foo(int &x) {
2 x = 20;
3}
4
5int main() {
6 int a = 10;
7 foo(a);
8 // The value of a is changed to 20
9 return 0;
10}✨ Special Parameter Types
Default Parameters
Default parameters allow you to specify default values for parameters in the function declaration. If the corresponding argument is not provided when calling the function, the default value is used. If the function definition is separate from the declaration, default parameters can only be specified in the declaration.
1#include <iostream>
2using namespace std;
3
4void displayInfo(string name = "Unknown", int age = 0) {
5 cout << "Name: " << name << ", Age: " << age << endl;
6}
7
8int main() {
9 displayInfo(); // Output: Name: Unknown, Age: 0
10 displayInfo("Bob"); // Output: Name: Bob, Age: 0
11 displayInfo("Charlie", 30); // Output: Name: Charlie, Age: 30
12 return 0;
13}Notes on default parameters:
- Default parameters must be specified from right to left. For example, you cannot specify a default value for the first parameter without specifying one for the second
- If the declaration and definition are separate, default parameters can only be specified in the declaration
1void func(int a, int b = 10, int c = 20); // Correct
2// void func(int a = 10, int b, int c = 20); // Error
3
4// Function declaration
5void showMessage(string message = "Hello");
6
7// Function definition
8void showMessage(string message) {
9 std::cout << message << std::endl;
10}
11
12int main() {
13 showMessage(); // Output: Hello
14 showMessage("Hi there!"); // Output: Hi there!
15 return 0;
16}Array Parameters
Array parameters may look like pass by value syntactically, but they actually pass the starting address of the array. Therefore, modifying array elements inside the function also changes the array outside the function.
1#include <iostream>
2using namespace std;
3
4// Function using int a[] as parameter, can modify array elements
5void modifyArray(int a[], int size) {
6 for (int i = 0; i < size; ++i) {
7 a[i] += 10; // Add 10 to each element
8 }
9}
10
11int main() {
12 int arr[] = {1, 2, 3, 4, 5};
13 int size = sizeof(arr) / sizeof(arr[0]);
14
15 // Modify array elements
16 modifyArray(arr, size);
17
18 // Output modified array: 11 12 13 14 15
19 for (int i = 0; i < size; ++i) {
20 cout << arr[i] << (i + 1 == size ? "\n" : " ");
21 }
22 return 0;
23}Notes on array parameters:
- In the function declaration, you only need to add brackets
[]to indicate the parameter is an array — you do not need to specify the array size - An additional array size parameter is needed to assist with array operations
- Modifying array elements inside the function also affects them outside the function
✨ Execution Example of Function Parameters
Using "swapping two variables" as an example, we demonstrate the execution process of pass by value and pass by reference:
Pass by Value Execution
1void swapByValue(int x, int y) {
2 int temp = x;
3 x = y;
4 y = temp;
5}
6
7int main() {
8 int a = 3, b = 7;
9 swapByValue(a, b);
10 cout << a << " " << b << endl; // Output: 3 7
11 return 0;
12}Step-by-step trace:
| Step | Operation | a (main) | b (main) | x (in function) | y (in function) |
|---|---|---|---|---|---|
| 1 | Initialize a=3, b=7 | 3 | 7 | - | - |
| 2 | Call swapByValue(a, b), copy values | 3 | 7 | 3 | 7 |
| 3 | temp = x (temp=3) | 3 | 7 | 3 | 7 |
| 4 | x = y | 3 | 7 | 7 | 7 |
| 5 | y = temp | 3 | 7 | 7 | 3 |
| 6 | Function returns, x and y are destroyed | 3 | 7 | - | - |
Result: The values of a and b did not change because the function only modified copies.
Pass by Reference Execution
1void swapByRef(int &x, int &y) {
2 int temp = x;
3 x = y;
4 y = temp;
5}
6
7int main() {
8 int a = 3, b = 7;
9 swapByRef(a, b);
10 cout << a << " " << b << endl; // Output: 7 3
11 return 0;
12}Step-by-step trace:
| Step | Operation | a / x (same variable) | b / y (same variable) |
|---|---|---|---|
| 1 | Initialize a=3, b=7 | 3 | 7 |
| 2 | Call swapByRef(a, b), x is a reference to a, y is a reference to b | 3 | 7 |
| 3 | temp = x (temp=3) | 3 | 7 |
| 4 | x = y (i.e., a = b) | 7 | 7 |
| 5 | y = temp (i.e., b = 3) | 7 | 3 |
| 6 | Function returns | 7 | 3 |
Result: The values of a and b were successfully swapped because x and y are a and b themselves.
✨ Problem-Solving Steps for Function Parameters
Example: Write a function to find the maximum and minimum values in an array
Analysis:
- The function needs to return multiple values: The maximum and minimum are two results, but a regular return can only return one value, so we need pass by reference to "carry out" multiple results
- Design the function signature:
void findMinMax(int arr[], int n, int &minVal, int &maxVal) - Write the function body: Iterate through the array, updating the maximum and minimum values
- Call the function: Declare variables in the main function, pass them to the function, and after the function returns, the variables will contain the results
1void findMinMax(int arr[], int n, int &minVal, int &maxVal) {
2 minVal = arr[0];
3 maxVal = arr[0];
4 for (int i = 1; i < n; ++i) {
5 if (arr[i] < minVal) minVal = arr[i];
6 if (arr[i] > maxVal) maxVal = arr[i];
7 }
8}
9
10int main() {
11 int a[] = {4, 1, 7, 3, 9};
12 int minV, maxV;
13 findMinMax(a, 5, minV, maxV);
14 cout << "Min: " << minV << " Max: " << maxV << endl;
15 // Output: Min: 1 Max: 9
16 return 0;
17}Key idea: When a function needs to "return" multiple values, use pass by reference to let the function directly modify the caller's variables.
✨ Common Mistakes with Function Parameters
- Using pass by value but expecting the original variable to change: The classic mistake is writing a swap function without the
&, so the swap happens inside the function but the external variables remain unchanged - Specifying array size in the parameter: The
10invoid func(int a[10])is ignored by the compiler, which can be misleading — useint a[]instead - Forgetting to pass the array size: After passing an array to a function, you cannot use
sizeofto find its length — you must pass an additionalint nparameter - Wrong order of default parameters: Default parameters must be specified from right to left continuously — you cannot skip middle parameters. For example,
void f(int a = 1, int b, int c = 3)is incorrect - Writing default values in both declaration and definition: If the function declaration and definition are separate, default parameters should only be in the declaration — having them in both causes a compilation error