C++: Function Basics

Last updated: 2026-08-26

In previous lessons, all code was written inside the main function.

But as programs grow larger, the main function 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):

CPP
#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):

CPP
#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

TEXT 📖 Display only
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 ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
3 + 5 = 8


3. Function Calls

(1) 3.1 Call Syntax

TEXT 📖 Display only
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:

  1. Return a result to the caller
  2. End the function (code after return won't execute)
CPP
#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:

CPP
#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.

TEXT 📖 Display only
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

CPP
#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:

TEXT 📖 Display only
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.

CPP
#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:



6. Practice: Calculator with Functions

▶ Example 2: Calculator Using Functions (Difficulty ⭐⭐)

CPP 📖 Display only
#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;
}
49 logic lines (exceeds 40-line limit, display only)

Output:

TEXT 📖 Display only
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:

TEXT 📖 Display only
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:

CPP
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:

TEXT 📖 Display only
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:

CPP
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

Q Can parameter names be omitted in function prototypes?
A Yes, but it's recommended to keep them. int add(int, int); is syntactically valid; int add(int a, int b); is recommended for readability.
Q Can a function return multiple values?
A A C++ function can only have one return value. But you can "return" multiple values using: 1. Pointer or reference parameters (covered later) 2. Returning a struct or class (covered later) 3. Using std::tuple (C++11 and later)
Q Can I write return in a void function?
A Yes! return; (without a value) can exit a void function early.
Q Why does my function defined after main compile successfully?
A The compiler might be "lenient," or you may have inadvertently written a function prototype. Recommendation: always put function prototypes before main and definitions after (or both before).

▶ Example 3: Function Return Value (Difficulty ⭐)

CPP
#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;
}
▶ Try it Yourself

Output:

TEXT 📖 Display only
Larger value: 20
💡 Tip: Functions can return computed results using return. The ternary operator ? : can simplify simple conditional checks.


📖 Summary


📝 Exercises

  1. Basic (Difficulty ⭐): Write a function int multiply(int a, int b) that returns the product of two integers. Call it in the main function.

  2. Intermediate (Difficulty ⭐⭐): Write a function bool isPrime(int n) that determines whether an integer is prime.

  3. Prime: a number only divisible by 1 and itself (e.g., 2, 3, 5, 7, 11)

  4. In the main function, let the user enter an integer, call isPrime, and output the result

  5. Challenge (Difficulty ⭐⭐⭐): Write a program with the following functions:

  6. int fibonacci(int n): returns the nth Fibonacci number

  7. 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.


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."

Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏