What is a Function?¶
In programming, a function is like a “code gadget” that encapsulates a specific block of code, allowing us to reuse it. For example, in mathematics, the function f(x) = 2x takes an input x and returns a corresponding result. Similarly, in C++, a function takes some data (parameters) and returns a result, or performs certain operations.
The most direct benefits of using functions are code reuse and clear structure. For instance, if we need to calculate the sum of two numbers multiple times, defining a function avoids repeating the addition code. Modifications only require changing the logic inside the function, not searching for duplicate code everywhere.
Function Definition¶
A function definition includes several parts: return type, function name, parameter list, and function body.
Basic Format:¶
returnType functionName(parameterType1 parameterName1, parameterType2 parameterName2, ...) {
// Function body: specific code to execute
return returnValue; // If returnType is void, return can be omitted or just "return;"
}
Example: Sum of Two Numbers¶
// Define a function that takes two int parameters and returns their sum
int add(int a, int b) { // a and b are formal parameters (shape parameters) representing received data
int sum = a + b; // Function body: calculate the sum of a and b
return sum; // Return the result (must match the return type)
}
- Return Type:
intmeans the function returns an integer. If the function has no return value, usevoid(e.g., a function that prints information). - Function Name:
addshould be descriptive (e.g.,addfor summation,swapfor swapping values). - Parameter List:
(int a, int b)contains parameters the function receives, each specifying a type and name. - Function Body: Code inside the curly braces
{}is the specific operation the function performs.
Function Call¶
After defining a function, it must be “called” elsewhere to execute. When calling a function, provide actual arguments (real parameters), which are copied to the formal parameters.
Call Format:¶
functionName(actualArgument1, actualArgument2, ...); // Call without return value
returnType variable = functionName(actualArgument1, actualArgument2, ...); // Receive result if returning a value
Example: Calling the add Function in main¶
#include <iostream>
using namespace std;
// Define the add function (from previous example)
int add(int a, int b) {
return a + b;
}
int main() {
int x = 5, y = 3;
// Call the add function with x and y as actual arguments
int result = add(x, y); // Receive the return value
cout << "5 + 3 = " << result << endl; // Output: 5 + 3 = 8
return 0;
}
Key Point: The type and number of actual arguments must match the formal parameters defined in the function (e.g., add requires two ints, so a string cannot be passed).
Types of Parameter Passing¶
Parameter passing is a core concept, with two main methods: pass-by-value (most common) and pass-by-reference (familiarize with pass-by-value first; pass-by-reference is briefly covered).
1. Pass-by-Value (Most Common)¶
Pass-by-value is the default method, where a copy of the actual argument is passed to the formal parameter. Modifying the formal parameter does not affect the actual argument.
Example: Behavior of Pass-by-Value¶
#include <iostream>
using namespace std;
// Pass-by-value: Modifying the formal parameter 'a' does not affect the actual argument
void changeValue(int a) {
a = 100; // Only modify the formal parameter 'a'
}
int main() {
int x = 10;
changeValue(x); // Call the function with x as the actual argument
cout << "Value of x: " << x << endl; // Output: Value of x: 10 (actual argument unchanged)
return 0;
}
Why? Because pass-by-value copies the actual argument’s value to the formal parameter. The formal parameter a is a “copy” of x, so modifying a does not affect x.
2. Pass-by-Reference (& Symbol)¶
To allow a function to modify the actual argument (e.g., swapping two variables), use pass-by-reference. Pass-by-reference uses &, where the formal parameter is an alias for the actual argument, so modifying the formal parameter directly affects the actual argument.
Example: Swap Using Pass-by-Reference¶
#include <iostream>
using namespace std;
// Pass-by-reference: Formal parameters are aliases for actual arguments
void swap(int &a, int &b) { // a and b reference the actual arguments x and y
int temp = a;
a = b;
b = temp;
}
int main() {
int x = 5, y = 10;
swap(x, y); // Call with actual arguments x and y
cout << "x = " << x << ", y = " << y << endl; // Output: x = 10, y = 5
return 0;
}
Key Point: Pass-by-reference requires the & symbol, and actual arguments must be variables (not constants or expressions).
3. Default Parameters (Optional Parameters)¶
During function definition, you can set default values for parameters. If not provided during a call, the default value is used, simplifying the call logic.
Example: Default Parameters¶
#include <iostream>
using namespace std;
// Set a default value of 2 for the second parameter
int power(int base, int exponent = 2) {
int result = 1;
for (int i = 0; i < exponent; i++) {
result *= base;
}
return result;
}
int main() {
cout << "Square of 3: " << power(3) << endl; // Use default exponent=2 → 9
cout << "4th power of 3: " << power(3, 4) << endl; // Use custom exponent=4 → 81
return 0;
}
Note: Default parameters must be specified from right to left (e.g., exponent=2 must come after base), otherwise the compiler will throw an error.
Function Declaration and Definition Order¶
If a function is defined after the code that calls it (e.g., in main), it must be declared first. A function declaration tells the compiler, “This function exists, with this return type and parameter list.”
Example: Function Declaration¶
#include <iostream>
using namespace std;
// Function declaration: Inform the compiler about the function
int multiply(int a, int b); // Ends with semicolon, no function body needed
int main() {
int result = multiply(4, 5);
cout << "4 * 5 = " << result << endl; // Output: 20
return 0;
}
// Function definition: Implement the function logic
int multiply(int a, int b) {
return a * b;
}
Summary¶
- Function Definition: Return type + function name + parameter list + function body. Clearly define its purpose.
- Function Call: Use
functionName(actualArguments); receive the return value if applicable (usevoidfor no return value). - Parameter Passing:
- Pass-by-value: Formal parameters are copies of actual arguments; modifying them does not affect the actual arguments.
- Pass-by-reference: Use
&; formal parameters are aliases of actual arguments, so modifications affect the actual arguments. - Default Parameters: Simplify calls; set from right to left.
Exercise: Try writing a small program with add (sum two numbers), swap (swap two numbers), and power (calculate exponents). Practice defining and calling functions!