Chapter 7: Functions
Functions in C++: The Superpower of Organized & Reusable Code
Hello my brilliant student! π Welcome to one of the most important chapters in all of programming β Functions!
Until now, all our code lived inside main(). That works for tiny programs, but real software is built by breaking big problems into small, reusable pieces β and functions are exactly those pieces.
Think of functions like:
- Recipes in a cookbook (you can reuse them anytime)
- Tools in a toolbox (hammer, screwdriver β each does one job well)
- Mini-programs that you can call whenever you need them
Today weβll cover everything about functions in great detail:
- Defining & calling functions
- Parameters: pass by value, pass by reference, pass by pointer
- Return types
- Function overloading
- Default arguments
- Inline functions
- constexpr functions (modern C++ magic!)
Weβll go step-by-step with tons of examples, analogies, common mistakes, and best practices.
Letβs start writing reusable code!
1. Defining & Calling a Function β The Basics
Syntax to define a function:
|
0 1 2 3 4 5 6 7 8 9 |
returnType functionName(parameterList) { // code here return someValue; // if returnType is not void } |
Example β Very simple function:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
#include <iostream> // Function definition void sayHello() { std::cout << "Hello from the sayHello function!\n"; } int main() { // Calling (using) the function sayHello(); // prints: Hello from the sayHello function! sayHello(); // You can call it as many times as you want! sayHello(); return 0; } |
Key points:
- void means no return value
- Function name should be meaningful (like calculateArea, printStudentInfo)
- You must define or at least declare the function before you call it (or use forward declaration β see later)
2. Functions with Parameters & Return Values
Parameters = inputs to the function Return value = output from the function
Example β Function that adds two numbers:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
#include <iostream> // Function that takes two ints and returns their sum int add(int a, int b) { int result = a + b; return result; // or simply: return a + b; } int main() { int x = 15; int y = 27; int sum = add(x, y); // calling the function std::cout << x << " + " << y << " = " << sum << "\n"; // You can also call it directly in cout std::cout << "10 + 20 = " << add(10, 20) << "\n"; return 0; } |
3. Three Ways to Pass Parameters
This is very important β many beginners get confused here!
| Method | Syntax in function | What happens to original variable? | When to use? |
|---|---|---|---|
| Pass by value | int add(int a, int b) | Copy is made β original unchanged | Default & safest |
| Pass by reference | int add(int& a, int& b) | Works directly on original variable | When you want to modify the argument |
| Pass by pointer | int add(int* a, int* b) | Uses pointer β can modify original | Older style, C compatibility, optional parameters |
A. Pass by Value (Default & Safest)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
void increment(int x) { x = x + 1; // only changes the local copy std::cout << "Inside function: x = " << x << "\n"; } int main() { int num = 10; increment(num); std::cout << "After function: num = " << num << "\n"; // Still 10! } |
B. Pass by Reference (Modern & Recommended)
Use & after the type:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
void increment(int& x) { // β reference! x = x + 1; std::cout << "Inside: x = " << x << "\n"; } int main() { int num = 10; increment(num); std::cout << "After: num = " << num << "\n"; // Now 11! } |
Very common pattern β swap two numbers:
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
void swap(int& a, int& b) { int temp = a; a = b; b = temp; } int main() { int x = 5, y = 10; std::cout << "Before: x=" << x << ", y=" << y << "\n"; swap(x, y); std::cout << "After: x=" << x << ", y=" << y << "\n"; // Output: x=10, y=5 } |
C. Pass by Pointer (Older style β still useful)
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
void increment(int* ptr) { (*ptr) = (*ptr) + 1; // dereference pointer } int main() { int num = 100; increment(&num); // pass address std::cout << num << "\n"; // 101 } |
Modern advice (2025+): Use references (&) whenever you want to modify arguments β cleaner and safer than pointers.
4. Function Return Types
- void β no return
- int, double, bool, std::string β return that type
- Can return anything (even custom types later)
Multiple return values? Use references or std::pair / std::tuple (weβll see later).
5. Function Overloading β Same Name, Different Parameters
You can have multiple functions with the same name β as long as parameter lists differ (number or types).
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
void print(int n) { std::cout << "Integer: " << n << "\n"; } void print(double d) { std::cout << "Double: " << d << "\n"; } void print(const std::string& s) { std::cout << "String: " << s << "\n"; } int main() { print(42); // calls int version print(3.14159); // calls double version print("Hello!"); // calls string version } |
6. Default Arguments β Optional Parameters
You can give parameters default values β caller can skip them.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
void greet(std::string name = "Guest", int age = 0) { std::cout << "Hello " << name; if (age > 0) { std::cout << ", you are " << age << " years old!"; } std::cout << "\n"; } int main() { greet(); // Hello Guest greet("Webliance"); // Hello Webliance greet("Alice", 25); // Hello Alice, you are 25 years old! } |
Rule: Default arguments must be rightmost in the parameter list.
7. Inline Functions β Performance Boost
inline tells the compiler: βPlease copy-paste this functionβs code wherever I call itβ β no function call overhead.
|
0 1 2 3 4 5 6 7 8 |
inline double square(double x) { return x * x; } |
Modern reality (2025+): Most modern compilers inline small functions automatically β even without the keyword. Use inline mainly for:
- Very small functions used in performance-critical code
- When defining functions in header files (to avoid linker errors)
8. constexpr Functions β Compile-Time Magic (C++11+)
A constexpr function can be evaluated at compile time if all arguments are constants.
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
constexpr int factorial(int n) { return (n <= 1) ? 1 : n * factorial(n - 1); } int main() { constexpr int f5 = factorial(5); // computed at compile time! β 120 std::cout << f5 << "\n"; int x = 6; int f6 = factorial(x); // computed at runtime } |
Super useful for:
- Constants
- Array sizes
- Template metaprogramming
9. Full Practical Example β Student Management Functions
|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
#include <iostream> #include <string> #include <iomanip> void printStudent(const std::string& name, int roll, double marks) { std::cout << std::left << std::setw(20) << name << std::setw(10) << roll << std::fixed << std::setprecision(2) << marks << "\n"; } double calculatePercentage(double m1, double m2, double m3) { return (m1 + m2 + m3) / 3.0; } void getStudentInfo(std::string& name, int& roll, double& avg) { std::cout << "Enter name: "; std::getline(std::cin, name); std::cout << "Enter roll no: "; std::cin >> roll; double m1, m2, m3; std::cout << "Enter 3 marks: "; std::cin >> m1 >> m2 >> m3; avg = calculatePercentage(m1, m2, m3); } int main() { std::string name; int roll; double average; getStudentInfo(name, roll, average); std::cout << "\n=== Student Record ===\n"; std::cout << std::left << std::setw(20) << "Name" << std::setw(10) << "Roll" << "Average\n"; printStudent(name, roll, average); return 0; } |
Your Mini Homework (Try These!)
- Write a function isEven(int n) that returns true if n is even.
- Write an overloaded function max() that finds the maximum of:
- Two integers
- Three integers
- Two doubles
- Write a function power(double base, int exp = 2) that calculates base^exp (default square).
- Create a function that swaps two strings by reference.
Youβre doing absolutely amazing! Functions are the foundation of clean, maintainable code β youβve just unlocked the ability to write real software!
Next lesson: Arrays & Strings β storing lots of data!
Any questions? Confused about pass-by-reference vs pointer? Want more examples of overloading or constexpr? Just ask β your friendly C++ teacher is right here! π
