C++ Programming
Functions
Mastering functions concepts and implementation.
On this page
Functions
Functions are reusable blocks of code that perform specific tasks. They help organize code, reduce duplication, and make programs easier to understand and maintain.
What are Functions?
A function is a named block of code that:
- Takes input (parameters)
- Performs operations
- Returns output (return value)
Benefits:
- Code Reusability: Write once, use many times
- Modularity: Break complex programs into smaller pieces
- Maintainability: Fix bugs in one place
- Readability: Descriptive names make code self-documenting
- Testing: Test individual functions independently
Function Syntax
Basic Structure:
1return_type function_name(parameter_list) {
2 // function body
3 return value;
4}
Components:
- Return Type: Data type of the value returned (use
voidif nothing returned) - Function Name: Identifier for the function
- Parameters: Input values (can be empty)
- Function Body: Code that executes
- Return Statement: Value to return (optional for
void)
Types of Functions
1. Functions with No Parameters and No Return
Example:
1void greet() {
2 cout << "Hello, World!" << endl;
3}
4
5int main() {
6 greet(); // Call the function
7 return 0;
8}
Sample Output
Hello, World!
2. Functions with Parameters
Example:
1void greet(string name) {
2 cout << "Hello, " << name << "!" << endl;
3}
4
5int main() {
6 greet("Alice");
7 greet("Bob");
8 return 0;
9}
Sample Output
Hello, !
3. Functions with Return Value
Example:
1int add(int a, int b) {
2 return a + b;
3}
4
5int main() {
6 int result = add(5, 3);
7 cout << "Sum: " << result << endl;
8 return 0;
9}
Sample Output
Sum:
4. Functions with Multiple Parameters
Example:
1int multiply(int a, int b, int c) {
2 return a * b * c;
3}
4
5int main() {
6 int product = multiply(2, 3, 4);
7 cout << "Product: " << product << endl;
8 return 0;
9}
Sample Output
Product:
Function Declaration vs Definition
Function Declaration (Prototype)
Tells the compiler about a function before it's defined:
1int add(int a, int b); // Declaration
Function Definition
The actual implementation:
1int add(int a, int b) { // Definition
2 return a + b;
3}
Why use declarations?
- Allows functions to be called before they're defined
- Enables better code organization
- Required when functions call each other
Example:
1#include <iostream>
2using namespace std;
3
4// Function declarations
5int add(int a, int b);
6int multiply(int a, int b);
7
8int main() {
9 cout << add(5, 3) << endl;
10 cout << multiply(4, 6) << endl;
11 return 0;
12}
13
14// Function definitions
15int add(int a, int b) {
16 return a + b;
17}
18
19int multiply(int a, int b) {
20 return a * b;
21}
Parameter Passing
Pass by Value
Creates a copy of the argument. Changes don't affect original:
1void increment(int x) {
2 x++; // Only changes local copy
3 cout << "Inside function: " << x << endl;
4}
5
6int main() {
7 int num = 5;
8 increment(num);
9 cout << "Outside function: " << num << endl; // Still 5
10 return 0;
11}
Sample Output
Inside function: Outside function:
Pass by Reference
Uses the original variable. Changes affect original:
1void increment(int& x) { // & means reference
2 x++; // Changes original
3 cout << "Inside function: " << x << endl;
4}
5
6int main() {
7 int num = 5;
8 increment(num);
9 cout << "Outside function: " << num << endl; // Now 6
10 return 0;
11}
Sample Output
Inside function: Outside function:
Pass by Pointer
Passes memory address. Changes affect original:
1void increment(int* x) { // * means pointer
2 (*x)++; // Dereference and increment
3 cout << "Inside function: " << *x << endl;
4}
5
6int main() {
7 int num = 5;
8 increment(&num); // Pass address
9 cout << "Outside function: " << num << endl; // Now 6
10 return 0;
11}
Sample Output
Inside function: Outside function:
When to use each:
- Pass by Value: Small data, don't need to modify original
- Pass by Reference: Need to modify original, avoid copying large objects
- Pass by Pointer: Optional parameters, arrays, C compatibility
Default Parameters
Provide default values for parameters:
1int power(int base, int exponent = 2) {
2 int result = 1;
3 for (int i = 0; i < exponent; i++) {
4 result *= base;
5 }
6 return result;
7}
8
9int main() {
10 cout << power(3) << endl; // Uses default: 3^2 = 9
11 cout << power(3, 3) << endl; // Override: 3^3 = 27
12 return 0;
13}
Rules:
- Default parameters must be rightmost
- Once a parameter has a default, all following must have defaults
Function Overloading
Multiple functions with same name but different parameters:
1int add(int a, int b) {
2 return a + b;
3}
4
5double add(double a, double b) {
6 return a + b;
7}
8
9int add(int a, int b, int c) {
10 return a + b + c;
11}
12
13int main() {
14 cout << add(5, 3) << endl; // Calls int version
15 cout << add(5.5, 3.2) << endl; // Calls double version
16 cout << add(1, 2, 3) << endl; // Calls 3-parameter version
17 return 0;
18}
Rules:
- Functions must differ in number or types of parameters
- Return type alone is NOT enough for overloading
Recursion
Function that calls itself:
1int factorial(int n) {
2 if (n <= 1) {
3 return 1; // Base case
4 }
5 return n * factorial(n - 1); // Recursive case
6}
7
8int main() {
9 cout << factorial(5) << endl; // 120
10 return 0;
11}
Important:
- Must have a base case (stopping condition)
- Each recursive call should move toward base case
- Can be memory-intensive for deep recursion
Example: Fibonacci
1int fibonacci(int n) {
2 if (n <= 1) {
3 return n;
4 }
5 return fibonacci(n - 1) + fibonacci(n - 2);
6}
Inline Functions
Small functions that are expanded inline (compiler suggestion):
1inline int square(int x) {
2 return x * x;
3}
4
5int main() {
6 int result = square(5); // May be expanded inline
7 return 0;
8}
Use when:
- Function is small and called frequently
- Want to avoid function call overhead
- Note: Modern compilers often inline automatically
Lambda Functions (C++11)
Anonymous functions defined inline:
1auto add = [](int a, int b) {
2 return a + b;
3};
4
5int result = add(5, 3);
Syntax:
1[capture](parameters) -> return_type { body }
Example:
1#include <iostream>
2#include <vector>
3#include <algorithm>
4using namespace std;
5
6int main() {
7 vector<int> numbers = {1, 2, 3, 4, 5};
8
9 // Lambda to double each number
10 for_each(numbers.begin(), numbers.end(),
11 [](int& n) { n *= 2; });
12
13 // Lambda to print
14 for_each(numbers.begin(), numbers.end(),
15 [](int n) { cout << n << " "; });
16
17 return 0;
18}
Common Function Patterns
Pattern 1: Validation Function
1bool isValidAge(int age) {
2 return age >= 0 && age <= 150;
3}
Pattern 2: Calculation Function
1double calculateArea(double radius) {
2 const double PI = 3.14159;
3 return PI * radius * radius;
4}
Pattern 3: Utility Function
1int max(int a, int b) {
2 return (a > b) ? a : b;
3}
Pattern 4: Multiple Return Values (using references)
1void divide(int dividend, int divisor, int& quotient, int& remainder) {
2 quotient = dividend / divisor;
3 remainder = dividend % divisor;
4}
Best Practices
- ✅ Use descriptive function names (
calculateAreanotcalc) - ✅ Keep functions small (single responsibility)
- ✅ Use const for parameters that shouldn't be modified
- ✅ Document with comments for complex functions
- ✅ Return early for error cases
- ✅ Avoid global variables - pass as parameters instead
- ✅ Use references to avoid copying large objects
- ✅ One function, one purpose
Common Mistakes
- ❌ Forgetting return statement (for non-void functions)
- ❌ Modifying parameters when you shouldn't (use const)
- ❌ Functions too long (hard to understand)
- ❌ Too many parameters (consider struct/class)
- ❌ Infinite recursion (no base case)
- ❌ Not handling edge cases
Next Module
In Module 6, we'll learn about Arrays and Strings - how to work with collections of data and text!
Hands-on Examples
Basic Functions
#include <iostream>
#include <string>
using namespace std;
// Function with no parameters
void greet() {
cout << "Hello, World!" << endl;
}
// Function with parameters
void greetPerson(string name) {
cout << "Hello, " << name << "!" << endl;
}
// Function with return value
int add(int a, int b) {
return a + b;
}
// Function with multiple parameters
int multiply(int a, int b, int c) {
return a * b * c;
}
int main() {
greet();
greetPerson("Alice");
greetPerson("Bob");
int sum = add(10, 20);
cout << "Sum: " << sum << endl;
int product = multiply(2, 3, 4);
cout << "Product: " << product << endl;
return 0;
}Functions can have no parameters, one parameter, multiple parameters, or return values. Functions help organize code and make it reusable.
Sample Output
Hello, World! Hello, Alice! Hello, Bob! Sum: 30 Product: 24
Practice with Programs
Reinforce your learning with hands-on practice programs
Related Program Topics
Recommended Programs
Hello World
BeginnerWrite your first C++ program and see why each of its four lines matters: #include, using namespace std, main, cout, and return 0. Made for day-one students.
Display Your Name
BeginnerStore your name in a C++ string variable and print it with cout and endl. Covers #include <string>, chaining <<, and how a string differs from a char array.
User Input
BeginnerRead a name and an age from the keyboard with cin in C++. See why cin >> stops at the first space, when to use getline, and how a bad number breaks the stream.
Check for Even Odd
BeginnerCheck whether an integer is even or odd in C++ using the % operator and an if/else. Covers zero, negative numbers, and why == 1 is the wrong test for odd.
Largest Among 3
BeginnerFind the largest of three numbers in C++ with an if / else if / else chain and the && operator. Shows why >= matters when two inputs tie for the maximum.