C++: Function Basics
Last updated: 2026-08-26
In previous lessons, all code was written inside the
mainfunction.But as programs grow larger, the
mainfunction becomes long and hard to maintain.Functions solve this problem — dividing code into small modules, each responsible for one task.
1. What is a Function?
(1) 1.1 Functions in Everyday Life
| Real-life scenario | Programming equivalent |
|---|---|
| You press the "power" button on the TV remote | Calling the turnOnTV() function |
| The TV automatically performs a series of operations (power on, search channels, display picture) | The code inside the function body |
| You don't need to know how the TV works internally | The "encapsulation" property of functions |
A function is a block of code that performs a specific task, which you can call repeatedly.
(2) 1.2 Why Do We Need Functions?
Without functions (bad example):
#include <iostream>
int main() {
// Calculate area of the first rectangle
double width1 = 5.0, height1 = 3.0;
double area1 = width1 * height1;
std::cout << "Area 1: " << area1 << std::endl;
// Calculate area of the second rectangle
double width2 = 7.0, height2 = 2.5;
double area2 = width2 * height2;
std::cout << "Area 2: " << area2 << std::endl;
// Calculate area of the third rectangle
double width3 = 4.0, height3 = 6.0;
double area3 = width3 * height3;
std::cout << "Area 3: " << area3 << std::endl;
return 0;
}
With functions (good example):
#include <iostream>
// Define the function
double calculateArea(double width, double height) {
return width * height;
}
int main() {
std::cout << "Area 1: " << calculateArea(5.0, 3.0) << std::endl;
std::cout << "Area 2: " << calculateArea(7.0, 2.5) << std::endl;
std::cout << "Area 3: " << calculateArea(4.0, 6.0) << std::endl;
return 0;
}
Comparison:
| Without Functions | With Functions |
|---|---|
| Code duplication (copy and paste) | Code reuse (write once) |
| Changing logic requires changes in multiple places | Only change the function body in one place |
| Hard to maintain | Easy to maintain |
2. Function Definition
(1) 2.1 Basic Syntax
ReturnType functionName(parameterList) {
// function body
return returnValue; // if return type is not void
}
(2) 2.2 Parts of a Function
| Part | Meaning | Example |
|---|---|---|
| Return type | The type of value the function returns | int, double, void (no return) |
| Function name | The name of the function (follows variable naming rules) | calculateArea, printHello |
| Parameter list | The inputs the function receives (can be empty) | (double w, double h) |
| Function body | The code the function executes | { return w * h; } |
| return | Returns the result to the caller | return area; |
▶ Example 1: Define a Simple Function (Difficulty ⭐)
#include <iostream>
// Function definition: calculate the sum of two numbers
int add(int a, int b) {
return a + b;
}
int main() {
int result = add(3, 5); // Call the function
std::cout << "3 + 5 = " << result << std::endl;
return 0;
}
Output:
3 + 5 = 8
3. Function Calls
(1) 3.1 Call Syntax
functionName(argumentList);
| Term | Meaning | Example |
|---|---|---|
| Function definition | Writing the function's code | int add(int a, int b) { ... } |
| Function call | Using the function | add(3, 5); |
| Formal parameter (parameter) | Parameters in the function definition | int a, int b |
| Actual parameter (argument) | Values passed when calling the function | 3, 5 |
💡 Key point: Arguments are copied to parameters (we'll learn about references later, where copying isn't needed).
4. Return Values
(1) 4.1 The return Statement
return has two purposes:
- Return a result to the caller
- End the function (code after return won't execute)
#include <iostream>
int max(int a, int b) {
if (a > b) {
return a; // End function, return a
} else {
return b; // End function, return b
}
std::cout << "This line never executes" << std::endl; // Dead code
}
int main() {
std::cout << "Maximum: " << max(10, 20) << std::endl;
return 0;
}
(2) 4.2 Functions Without Return Values (void)
If a function doesn't need to return a value, use void as the return type:
#include <iostream>
void printWelcome() { // void means no return value
std::cout << "========== Welcome ==========" << std::endl;
std::cout << "This is a void function, no return needed" << std::endl;
}
int main() {
printWelcome(); // Call void function, no need to receive a return value
return 0;
}
💡 Tip: You can also write return; (without a value) in a void function to exit early.
void printIfPositive(int x) {
if (x <= 0) {
return; // Exit the function early
}
std::cout << x << " is positive" << std::endl;
}
5. Function Prototypes (Function Declarations)
(1) 5.1 The Problem: Functions Must Be Defined Before They Are Called
#include <iostream>
int main() {
std::cout << add(3, 5) << std::endl; // ❌ Error: compiler hasn't seen add's definition yet
return 0;
}
int add(int a, int b) {
return a + b;
}
Compile error message:
error: 'add' was not declared in this scope
(2) 5.2 Solution: Function Prototypes
A function prototype (also called a function declaration) tells the compiler "such a function exists," while the actual function body can be defined later.
#include <iostream>
int add(int a, int b); // Function prototype (ends with semicolon!)
int main() {
std::cout << add(3, 5) << std::endl; // ✅ Compiler knows add exists
return 0;
}
int add(int a, int b) { // Function definition
return a + b;
}
💡 Rules:
- Function prototypes end with a semicolon
- Parameter names can be omitted, only types needed:
int add(int, int); - But it's recommended to keep parameter names for readability
6. Practice: Calculator with Functions
▶ Example 2: Calculator Using Functions (Difficulty ⭐⭐)
#include <iostream>
#include <iomanip>
// Function prototypes
double add(double a, double b);
double subtract(double a, double b);
double multiply(double a, double b);
double divide(double a, double b);
int main() {
double num1, num2;
char op;
std::cout << "Please enter the first number: ";
std::cin >> num1;
std::cout << "Please enter an operator (+ - * /): ";
std::cin >> op;
std::cout << "Please enter the second number: ";
std::cin >> num2;
std::cout << std::fixed << std::setprecision(2);
switch (op) {
case '+':
std::cout << "Result: " << add(num1, num2) << std::endl;
break;
case '-':
std::cout << "Result: " << subtract(num1, num2) << std::endl;
break;
case '*':
std::cout << "Result: " << multiply(num1, num2) << std::endl;
break;
case '/':
if (num2 != 0) {
std::cout << "Result: " << divide(num1, num2) << std::endl;
} else {
std::cout << "Error: Divisor cannot be 0!" << std::endl;
}
break;
default:
std::cout << "Error: Unsupported operator!" << std::endl;
break;
}
return 0;
}
// Function definitions
double add(double a, double b) {
return a + b;
}
double subtract(double a, double b) {
return a - b;
}
double multiply(double a, double b) {
return a * b;
}
double divide(double a, double b) {
return a / b;
}
Output:
Please enter the first number:
Please enter an operator (+ - * /):
Please enter the second number:
Result:
Result:
Result:
Result:
Error: Divisor cannot be 0!
Error: Unsupported operator!
7. Common Errors
(1) 7.1 Forgetting to Write a Function Prototype
Error:
int main() {
foo(); // ❌ Compiler doesn't know what foo is yet
return 0;
}
void foo() {
std::cout << "Hello" << std::endl;
}
Fix: Add a function prototype:
void foo(); // ✅ Function prototype
int main() {
foo();
return 0;
}
void foo() {
std::cout << "Hello" << std::endl;
}
(2) 7.2 Function Prototype and Definition Don't Match
Error:
int foo(int a); // Prototype: returns int
int main() {
foo(5);
return 0;
}
double foo(int a) { // ❌ Error: definition returns double, doesn't match prototype
return a + 0.5;
}
(3) 7.3 Forgetting to Write return
Error:
int add(int a, int b) {
int sum = a + b;
// ❌ Forgot to write return
}
int main() {
int result = add(3, 5);
std::cout << result << std::endl; // Outputs garbage value
return 0;
}
💡 Tip: The C++ compiler may not warn you about a missing return, but the program's behavior is undefined (might output garbage, might crash).
❓ FAQ
int add(int, int); is syntactically valid; int add(int a, int b); is recommended for readability.std::tuple (C++11 and later)return; (without a value) can exit a void function early.▶ Example 3: Function Return Value (Difficulty ⭐)
#include <iostream>
int max(int a, int b) {
return (a > b) ? a : b;
}
int main() {
int x = 10, y = 20;
std::cout << "Larger value: " << max(x, y) << std::endl;
return 0;
}
Output:
Larger value: 20
return. The ternary operator ? : can simplify simple conditional checks.
📖 Summary
- Functions are blocks of code that perform specific tasks and can be reused
- Function definition syntax:
ReturnType functionName(parameterList) { functionBody } - Function prototypes tell the compiler a function exists, ending with a semicolon
returnreturns a result and ends the functionvoidfunctions don't return a value- Functions can be declared first (prototype) and defined later
📝 Exercises
-
Basic (Difficulty ⭐): Write a function
int multiply(int a, int b)that returns the product of two integers. Call it in themainfunction. -
Intermediate (Difficulty ⭐⭐): Write a function
bool isPrime(int n)that determines whether an integer is prime. -
Prime: a number only divisible by 1 and itself (e.g., 2, 3, 5, 7, 11)
-
In the
mainfunction, let the user enter an integer, callisPrime, and output the result -
Challenge (Difficulty ⭐⭐⭐): Write a program with the following functions:
-
int fibonacci(int n): returns the nth Fibonacci number -
void printFibonacci(int n): outputs the first n Fibonacci numbers
In the main function, let the user enter n, first output the first n numbers, then output the value of the nth number.
- Functions are reusable code blocks that reduce repetition
- Function four elements: return type, function name, parameter list, function body
- Function prototype declarations let the compiler know the function exists
- return returns a value and ends function execution
- void functions don't return a value; can use return; to exit early
12. 🚀 Next Step
Now that you've learned function basics, next we'll learn function parameter passing (Lesson 11) — learning how to pass parameters to functions and the difference between "pass by value" and "pass by reference."