PCCBSIT 003 - Computer
Programming 2 (Intermediate
Programming)
Module 4
Jayson S. Nacorda, MIT
Faculty
-
C++ Functions
In C++, functions are fundamental building blocks used to organize code into reusable,
maintainable, and logical units. A function is essentially a named block of code designed to perform
a specific task. Functions promote cleaner program structure, reduce duplication, and make
debugging easier.
📌 1. Purpose of Functions in C++
Functions serve several key purposes:
1. Code Reusability
You write the logic once and call it multiple times.
2. Modularity
Large programs are broken into smaller, manageable components.
3. Abstraction
The user of a function doesn’t need to know how it works—only how to use it.
4. Easier Testing & Maintenance
Each function can be tested independently, making the code easier to maintain.
📌 2. Basic Structure of a C++ Function
A function in C++ typically has:
1. Return type – the data type of the value returned (e.g., int, double, void)
2. Function name – identifier used to call the function
3. Parameters – optional input values
4. Function body – the code executed when the function is called
Syntax Example
return_type functionName(parameter_list) {
// function body
}
📌 3. Example of a Simple Function
Function Definition:
int add(int a,
Function Call:
int result = add(5, 3);
In this example:
int is the return type.
add is the function name.
(int a, int b) are the parameters.
return a + b; sends the result back to the caller.
Pre-defined Functions
A pre-defined function (also called built-in function or library function) is a function that is:
✔ Already written by C++ creators
✔ Stored inside library/header files
✔ Ready to use without writing the code yourself
✔ Helps perform common tasks quickly and easily
Examples of header files containing pre-defined functions:
Header Purpose
<iostream> Input/output functions (cout, cin)
<cmath> Math functions (sqrt, pow)
<cstring> String manipulation (strlen, strcpy)
<cstdlib> General utilities (rand, exit)
<ctime> Time-related functions (time)
You do not need to write the function manually—just call it, and C++ does the work.
⭐ Why Use Pre-defined Functions?
✔ Saves time
✔ Easier and faster than writing your own functions
✔ Reduces errors
✔ Standardized and tested
✔ Makes programs more powerful
⭐ REAL-WORLD EXAMPLE 1: Using
sqrt() to Compute Loan Interest
Distance
Imagine a bank app that needs to calculate the square root of a value (for example, in some risk
computations).
Instead of writing your own square root math function, you simply call:
sqrt(number);
This function comes from <cmath>.
✅ C++ PROGRAM (WITH LINE NUMBERS)
Using the pre-defined function sqrt():
1| #include <iostream>
2| #include <cmath> // contains sqrt()
3| using namespace std;
4|
5| int main() {
6|
7| double amount;
8| cout << "Enter a number to compute its square root: ";
9| cin >> amount;
10 |
11 | double result = sqrt(amount); // pre-defined function
12 |
13 | cout << "Square root of " << amount << " is: " << result << endl;
14 |
15 | return 0;
16 |}
⭐ LINE-BY-LINE EXPLANATION
Lines 1–2 — Include Libraries
1. <iostream> → for input/output
2. <cmath> → gives access to sqrt(), pow(), etc.
Lines 7–9 — Input
7. Declare a variable amount
8. Ask user to enter a number
9. Store the input
Line 11 — Pre-defined Function Call
11. sqrt(amount)
This function calculates the square root
No need to write your own formula
Result is stored in result
Line 13 — Output
13. Displays the computed square root
Line 15–16 — End Program
⭐ REAL-WORLD EXAMPLE 2: Random
Order Number Generator (rand())
Food delivery apps generate a random order number:
orderNumber = rand();
✅ PROGRAM: Generating Random Order
Number
1| #include <iostream>
2| #include <cstdlib> // contains rand()
3| using namespace std;
4|
5| int main() {
6|
7| int orderNumber = rand(); // pre-defined function
8|
9| cout << "Your Order Number: " << orderNumber << endl;
10 |
11 | return 0;
12 |}
⭐ Explanation
rand() automatically generates a random integer
Useful for:
✔ Order IDs
✔ OTP codes
✔ Random testing
⭐ REAL-WORLD EXAMPLE 3: Using
strlen() for Password Length Check
When signing up to a website, it checks if your password is long enough.
strlen(password);
⭐ PROGRAM: Checking Password
Length
1 | #include <iostream>
2| #include <cstring> // contains strlen()
3| using namespace std;
4|
5| int main() {
6|
7| char password[50];
8| cout << "Enter your password: ";
9| cin >> password;
10 |
11 | int length = strlen(password); // pre-defined function
12 |
13 | cout << "Password length: " << length << " characters\n";
14 |
15 | return 0;
16 |}
⭐ Explanation
strlen() counts characters in a C-style string
Useful for login systems and validations
⭐ Summary of Pre-Defined Function
Examples
Function Header Purpose
sqrt() <cmath> Math calculation
pow() <cmath> Exponent computation
rand() <cstdlib> Random number generation
strlen() <cstring> Checks string length
time() <ctime> Gets current time
User-Defined Functions
A user-defined function is a function that you (the programmer) create in order to:
Perform a specific task
Avoid repeating code
Organize the program into smaller sections
Make code cleaner, reusable, and easier to debug
A user-defined function has 3 parts:
1️⃣ Function Declaration (optional)
2️⃣ Function Definition
3️⃣ Function Call
Basic structure:
return_type functionName(parameters) {
// body of the function
}
void functionName(parameters) {
// body of the function
}
⭐ Why Do We Use User-Defined
Functions?
✔ To avoid repeating long blocks of code
✔ To make programs easier to read
✔ To allow dividing a program into meaningful, manageable parts
✔ To reuse the same logic many times
✔ To help in debugging and maintenance
⭐ REAL-WORLD EXAMPLE: Billing
System for a Store
A grocery store needs a function to compute total price by multiplying:
total = price × quantity
Instead of computing this everywhere, we create a user-defined function:
double computeTotal(double price, int qty);
✅ C++ PROGRAM (WITH LINE NUMBERS)
User-defined function: computeTotal()
1 | #include <iostream>
2| using namespace std;
3|
4| // User-defined function to compute total price
5| double computeTotal(double price, int quantity) {
6| double total = price * quantity;
7| return total; // return the computed value
8| }
9|
10 | int main() {
11 |
12 | double itemPrice;
13 | int itemQty;
14 |
15 | cout << "Enter item price: ";
16 | cin >> itemPrice;
17 |
18 | cout << "Enter item quantity: ";
19 | cin >> itemQty;
20 |
21 | // Calling the user-defined function
22 | double finalAmount = computeTotal(itemPrice, itemQty);
23 |
24 | cout << "Total amount to pay: ₱" << finalAmount << endl;
25 |
26 | return 0;
27 |}
⭐ LINE-BY-LINE EXPLANATION
📌 Lines 1–2 — Importing Libraries
1. #include <iostream> → Needed for input/output
2. using namespace std; → Allows using cout, cin without std::
⭐ PART 1 — User-Defined Function
Definition
Lines 4–8
4. Comment explaining the purpose
5. Function definition begins:
o double → return type
o computeTotal → function name
o (double price, int quantity) → parameters
6. Multiply price by quantity and store the result
7. Return the computed total back to main()
8. End of the user-defined function
➡ This function performs a calculation and returns a value.
⭐ PART 2 — Main Program Logic
Lines 12–14 — Declare Variables
12. Declare variable to store price
13. Declare variable to store quantity
Lines 15–20 — User Input
15–16. Ask and store item price
18–19. Ask and store item quantity
⭐ PART 3 — Calling the User-Defined
Function
Lines 21–23
22. Call the function:
computeTotal(itemPrice, itemQty);
This sends the values to the function.
23. Store returned value in finalAmount
➡ The function processes the data and returns the result.
⭐ PART 4 — Displaying the Result
Line 24
Show the computed final bill amount.
⭐ PART 5 — End Program
Lines 26–27
Return 0 → program completes successfully.
⭐ How It Works
1. User enters price and quantity
2. These values are passed into computeTotal()
3. The function multiplies them
4. The function returns the result
5. Main program prints total amount
Types of Functions in C++
1. Functions with Return Value
A function with a return value is a function that performs a task and sends a value back to the
part of the program that called it.
It uses:
return value;
And must specify a return type, such as:
int
double
string
char
bool
User-defined types (classes/structs)
A function with a return value must return something, unless the return type is void.
⭐ Why Do We Use Functions with
Return Value?
✔ To process data and bring back computed results
✔ To avoid repeating code
✔ To improve readability and organization
✔ To divide a program into smaller, manageable parts
✔ To reuse logic wherever needed
⭐ REAL-WORLD EXAMPLE: Online Store
Discount Calculator
A customer buys items online.
The store gives 10% discount if the total purchase amount is ₱1000 or higher.
We will create a function that returns the final price after discount.
✅ C++ PROGRAM WITH RETURN VALUE
1 | #include <iostream>
2 | using namespace std;
3|
4 | // Function with return value
5 | double calculateFinalPrice(double amount) {
6| if (amount >= 1000) {
7| return amount * 0.90; // apply 10% discount
8| }
9| return amount; // no discount
10 | }
11 |
12 | int main() {
13 |
14 | double purchaseAmount;
15 | cout << "Enter total purchase amount: ";
16 | cin >> purchaseAmount;
17 |
18 | // Function call with return value
19 | double finalPrice = calculateFinalPrice(purchaseAmount);
20 |
21 | cout << "Final price after discount: ₱" <<
✅ LINE-BY-LINE EXPLANATION
Lines 1–2 — Include library
1. iostream → used for input and output
2. using namespace std; → removes the need to write std::
⭐ PART 1 — Function Definition
Lines 4–10
4. Comment describing the function
5. Declare function:
o double = return type
o calculateFinalPrice = function name
o (double amount) = parameter
6. Check if purchase is ₱1000 or more
7. Apply 10% discount → return discounted price
8. If less than ₱1000 → return original amount
➡ Function returns a value back to main()
⭐ PART 2 — Program Logic
Lines 12–24
14. Ask user for amount
15–16. Read input
⭐ PART 3 — Function Call with Return
Value
Lines 18–20
19. Call the function
20. Store the returned value in finalPrice
⭐ PART 4 — Output
Line 21
Print the final discounted amount.
⭐ How It Works
1. User enters the amount
2. Amount is sent to the function
3. Function checks if discount applies
4. Function returns the final computed amount
5. main() receives the return value
6. Program displays the result
2. void Function
A void function is a function that performs an action but does not return a value.
Instead of sending information back using return, a void function typically:
Displays output
Performs a task
Updates data
Runs procedures
A void function uses:
void functionName() {
// code
}
If a function does not need to return a value, use void.
⭐ Why Do We Use void Functions?
✔ To organize code into smaller tasks
✔ To avoid repeating long blocks of code
✔ To separate actions from calculations
✔ To improve readability and structure
✔ To perform actions rather than compute values
⭐ REAL-WORLD EXAMPLE: ATM Receipt
Display
In an ATM machine:
After a withdrawal,
The machine prints a receipt showing the transaction details.
This "printing" action does not return a value, so it is perfect for a void function.
✅ C++ PROGRAM USING A void
FUNCTION
1 | #include <iostream>
2 | using namespace std;
3|
4 | // Void function to display a receipt
5 | void printReceipt(double balance, double withdraw) {
6| cout << "\n----- ATM RECEIPT -----\n";
7| cout << "Amount Withdrawn: ₱" << withdraw << endl;
8| cout << "Remaining Balance: ₱" << balance << endl;
9| cout << "Thank you for using our ATM!\n";
10 | }
11 |
12 | int main() {
13 |
14 | double balance = 5000;
15 | double withdraw;
16 |
17 | cout << "Enter amount to withdraw: ";
18 | cin >> withdraw;
19 |
20 | if (withdraw > balance) {
21 | cout << "Error: Insufficient balance.\n";
22 | return 0; // End program early
23 | }
24 |
25 | balance -= withdraw;
26 |
27 | // Calling the void function
28 | printReceipt(balance, withdraw);
29 |
30 | return 0;
31 | }
⭐ LINE-BY-LINE EXPLANATION
Lines 1–2 — Include Library
1. iostream → needed for input/output
2. using namespace std; → avoids typing std::
⭐ PART 1 — Declaring a void Function
Lines 4–10
4. Comment explaining what the function does
5. void printReceipt(...) means the function returns nothing
6. Display header "ATM Receipt"
7. Show amount withdrawn
8. Show remaining balance
9. Print final message
10. End of the function
This function does not compute or return anything, it only prints.
⭐ PART 2 — Main Program Logic
Lines 12–19 — Inputs
14. Set initial balance to ₱5000
15. Declare withdraw amount
16. Ask user for withdrawal value
17. Read input
⭐ PART 3 — Logic Before Calling Void
Function
Lines 20–26
20. Check if user tries to withdraw too much
21. Print error if insufficient balance
22. Exit program early
23. If valid, subtract withdrawal from balance
⭐ PART 4 — Calling the Void Function
Lines 27–31
28. Call the void function
29. Function prints receipt (no return value)
30–31. Program ends normally
⭐ How This Works
1. User enters withdrawal amount
2. Program checks if the amount is valid
3. If valid, balance is updated
4. A void function prints the receipt
5. The program finishes—no value is returned
3. Parameterized Functions
A parameterized function is a function that accepts values (parameters or arguments) when
it is called.
These parameters allow the function to process different data each time, making it more flexible
and powerful.
Example structure:
void functionName(parameter1, parameter2, ...) {
// code that uses the parameters
Parameters act like temporary variables used inside the function.
⭐ Why Do We Use Parameterized
Functions?
They help us:
✔ Pass information into functions
✔ Avoid repeating code
✔ Make programs flexible and reusable
✔ Calculate or process different input values
✔ Use functions like "tools" that accept custom data
⭐ REAL-WORLD EXAMPLE: Food
Delivery Fee Calculator
A food delivery app charges delivery fees based on:
Distance from store
Cost of the order
A function can compute the delivery fee, using these values as parameters.
✅ C++ PROGRAM USING
PARAMETERIZED FUNCTION
1 | #include <iostream>
2 | using namespace std;
3|
4 | // Parameterized function to calculate delivery fee
5 | double calculateDeliveryFee(double distance, double orderAmount) {
6|
7| double fee = 0;
8|
9| if (distance <= 3) {
10 | fee = 30; // base fee
11 | } else {
12 | fee = 30 + (distance - 3) * 5; // extra charge per km
13 | }
14 |
15 | // free delivery if order is 500 or above
16 | if (orderAmount >= 500) {
17 | return 0;
18 | }
19 |
20 | return fee;
21 | }
22 |
23 | int main() {
24 |
25 | double distance, amount;
26 |
27 | cout << "Enter distance from store (km): ";
28 | cin >> distance;
29 |
30 | cout << "Enter total order amount: ";
31 | cin >> amount;
32 |
33 | // calling the parameterized function
34 | double deliveryFee = calculateDeliveryFee(distance, amount);
35 |
36 | cout << "Delivery Fee: ₱" << deliveryFee << endl;
37 |
38 | return 0;
39 | }
⭐ LINE-BY-LINE EXPLANATION
📌 Lines 1–2 — Library
1. Includes input/output library
2. Allows use of standard library without std::
⭐ PART 1 — Parameterized Function
Definition
Lines 4–21
4. Comment describing the function
5. Function calculateDeliveryFee() has two parameters:
o distance → kilometers
o orderAmount → total purchase
Fee Calculation Logic
7. Declare a variable fee
9–13. Compute fee based on distance:
≤ 3 km → fee = 30
3 km → charge extra ₱5 per km
Free Delivery Rule
16. If orderAmount ≥ 500
17. Return 0 (free delivery)
Return Final Fee
20. Return computed delivery fee
⭐ PART 2 — Main Program
Lines 23–32 — Input
25. Declare distance and amount
27–29. Ask user for distance
30–31. Ask for order amount
⭐ PART 3 — Using the Parameterized
Function
Lines 33–37
34. Call the function and pass the inputs
35. Store returned value in deliveryFee
36. Display delivery fee
38–39. End program
⭐ How It Works
1. User enters distance and order amount
2. Function receives these values as parameters
3. Function calculates delivery fee
4. Function returns the fee to main()
5. Program displays the fee
4. Functions without Parameters
A function without parameters is a function that:
Does not take any input values
Performs a task entirely on its own
Uses only internal data or values available inside the function
Structure:
void functionName() {
// code
This type of function still works normally, but it does not receive any information from the
caller.
⭐ Why Do We Use Functions Without
Parameters?
We use them when:
✔ The function does not need any input
✔ The task is always the same
✔ Values are already known inside the function
✔ We want to organize and reuse code
✔ Simpler code is required for printing, displaying, or showing fixed messages
⭐ REAL-WORLD EXAMPLE: Restaurant
Menu Display System
When you open a food ordering app, the menu is displayed automatically—the app does NOT
need input to show the menu.
This is a great example of a function without parameters.
✅ C++ PROGRAM: Function Without
Parameters
1 | #include <iostream>
2 | using namespace std;
3|
4 | // Function without parameters to display a restaurant menu
5 | void displayMenu() {
6| cout << "----- WELCOME TO JAYSON'S RESTAURANT -----\n";
7| cout << "1. Fried Chicken - ₱120\n";
8| cout << "2. Burger Steak - ₱95\n";
9| cout << "3. Spaghetti - ₱80\n";
10 | cout << "4. Milk Tea - ₱60\n";
11 | cout << "-------------------------------------------\n";
12 | }
13 |
14 | int main() {
15 |
16 | // Call the function without parameters
17 | displayMenu();
18 |
19 | int choice;
20 | cout << "\nEnter your order number: ";
21 | cin >> choice;
22 |
23 | cout << "You selected menu item #" << choice << ".\n";
24 |
25 | return 0;
26 | }
⭐ LINE-BY-LINE EXPLANATION
📌 Lines 1–2 — Import Libraries
1. iostream → needed for input/output
2. using namespace std; → simplifies code (no std::)
⭐ PART 1 — Function Without
Parameters
Lines 4–12
4. Comment for understanding
5. Function displayMenu() declared with no parameters
6–11. Prints a menu list
6. End of the function
➡ This function does not return anything and does not accept anything.
It simply performs an action.
⭐ PART 2 — Main Program
Lines 14–26
16–17. Calls displayMenu()
➜ No arguments needed
➜ Menu prints automatically
19–21. Ask user to enter their choice
Example: 1 for Fried Chicken
23. Display the selected menu item number
25–26. End of program
⭐ How It Works
1. Program starts
2. Function displayMenu() is called
3. Menu appears on the screen
4. User picks an item
5. Program shows their selection
The function did not need any input, but still performed an important task.
5. Inline Functions
An inline function is a function where the compiler is requested to insert the function’s code
directly at the point of call, instead of jumping to a separate function memory location.
You declare it using the keyword:
inline
Example:
inline int square(int x) {
return x * x;
}
Instead of generating a normal function call, C++ may replace the call with the function code
itself.
⭐ Why Use Inline Functions?
Inline functions are used because they:
✔ Make execution faster
No need for the overhead of a function call.
✔ Are good for small, frequently used functions
Like mathematical formulas, simple return statements, getters, etc.
✔ Improve readability
Your code stays clean while still being efficient.
✔ Are safer than macros
Inline functions behave like normal functions (type-safe), unlike macros.
⭐ When Not to Use Inline Functions?
❌ Do NOT use inline for large functions
❌ Avoid using inline when the function has loops
❌ Avoid inline when the function is recursive
Because it can slow down the program and increase executable size.
⭐ REAL-WORLD EXAMPLE: E-Commerce
Delivery Estimate
An online shopping platform displays estimated delivery time based on distance.
The formula:
Delivery Time (in minutes) = distance * 5
This is a small, frequently called function → perfect for inline.
✅ C++ PROGRAM USING AN INLINE
FUNCTION
1 | #include <iostream>
2 | using namespace std;
3|
4 | // Inline function to compute delivery time
5 | inline int calculateDeliveryTime(int distance) {
6| return distance * 5; // 5 minutes per kilometer
7|}
8|
9 | int main() {
10 |
11 | int distance;
12 | cout << "Enter delivery distance (km): ";
13 | cin >> distance;
14 |
15 | // Calling the inline function
16 | int estimatedTime = calculateDeliveryTime(distance);
17 |
18 | cout << "Estimated delivery time: "
19 | << estimatedTime << " minutes\n";
20 |
21 | return 0;
22 | }
⭐ LINE-BY-LINE EXPLANATION
📌 Lines 1–2 — Header Files
1. #include <iostream> → For input/output
2. using namespace std; → Removes need for std::
⭐ PART 1 — Inline Function Definition
Lines 4–7
4. Comment: describes function
5. inline int calculateDeliveryTime(int distance)
o inline requests inline expansion
o int = return type
o distance = parameter
6. Return formula: distance * 5
➡ Very small → perfect for inline
➡ Compiler may replace calls with this exact code
⭐ PART 2 — Main Program Logic
Lines 11–14 — Input
11. Declare variable distance
12. Ask for delivery distance
13. User enters distance
⭐ PART 3 — Using the Inline Function
Lines 15–17
16. Call the inline function
17. Store the result in estimatedTime
The function may be expanded here like:
int estimatedTime = distance * 5;
⭐ PART 4 — Output
Lines 18–20
Print the estimated delivery time.
⭐ How Inline Functions Work
Normally a function call looks like this:
Call function → jump to function → run → return → jump back
But inline functions allow:
Replace the function call with the function code
This saves time but may increase program size if overused.
6. Recursive Functions
A recursive function is a function that calls itself in order to solve a problem.
It is useful when a problem can be broken down into smaller versions of itself, until it reaches a
“base case.”
A recursive function has two important parts:
1. Base Case
The stopping point of the recursion.
Prevents infinite repetition.
2. Recursive Case
The part where the function calls itself with a smaller or simpler input.
⭐ Why Use Recursive Functions?
Recursive functions are used for:
✔ Problems that repeat in smaller patterns
✔ Mathematical computations
✔ File system traversal
✔ Searching / sorting algorithms
✔ Real-world processes with steps that repeat
Examples of such tasks include:
Factorials
Fibonacci sequence
Counting items
Directory scanning
Processing hierarchical data
⭐ REAL-WORLD EXAMPLE: Counting
Items in a Warehouse Box
Imagine a warehouse where each box may contain more boxes, and those boxes may contain
items or more boxes.
To count all items, you need to:
1. Open a box
2. Count items inside
3. If there is another box, repeat the process
4. Stop when there are no more boxes
This is a recursive process, because each box can be treated as a smaller version of the whole
warehouse.
We will simulate this idea with a simple recursive function that counts down.
✅ C++ PROGRAM USING A RECURSIVE
FUNCTION
(Example: Counting down boxes to inspect)
1 | #include <iostream>
2 | using namespace std;
3|
4 | // Recursive function to count items in boxes
5 | void inspectBox(int boxNumber) {
6|
7| // Base Case: no more boxes to inspect
8| if (boxNumber == 0) {
9| cout << "All boxes have been inspected.\n";
10 | return;
11 | }
12 |
13 | // Recursive Case
14 | cout << "Inspecting box #" << boxNumber << endl;
15 |
16 | // Call the function again with a smaller number
17 | inspectBox(boxNumber - 1);
18 | }
19 |
20 | int main() {
21 |
22 | int boxes;
23 | cout << "Enter number of boxes to inspect: ";
24 | cin >> boxes;
25 |
26 | inspectBox(boxes); // Start the recursion
27 |
28 | return 0;
29 | }
⭐ LINE-BY-LINE EXPLANATION
📌 Lines 1–2 — Headers
1. Includes standard input/output library
2. Allows using C++ standard names without std::
⭐ PART 1 — Recursive Function
Definition
Lines 4–18
4. Comment describing the purpose of the function
5. inspectBox(int boxNumber) → function takes one integer parameter
Base Case — Stopping Condition
Lines 7–11:
7. This section checks whether there are no boxes left
8. If boxNumber == 0, then…
9. Print message: all boxes inspected
10. End function using return
➡ Prevents infinite recursion
➡ Tells recursion when to stop
Recursive Case — Keep Repeating
Lines 13–18:
14. Print which box is being inspected
15. Call inspectBox(boxNumber - 1)
Function calls itself
Each call decreases boxNumber
Moves toward base case
➡ Recursion continues until boxNumber becomes 0
⭐ PART 2 — Main Function
Lines 20–29
22–24. Ask user how many boxes there are
26. Start recursion by calling inspectBox(boxes)
Program prints each inspection task one by one until all boxes are done.
⭐ How Recursion Works (Simple
Breakdown)
If user enters: 5
Program flow:
inspectBox(5)
inspectBox(4)
inspectBox(3)
inspectBox(2)
inspectBox(1)
inspectBox(0) → stop
It goes deeper until base case
Then unwinds (returns back up).
⭐ Best Practices for Writing Functions
in C++
Good functions make programs easier to read, maintain, debug, and reuse.
Here are the most important best practices every programmer should follow:
✅ 1. Use Meaningful and Descriptive
Function Names
Your function name should clearly describe what it does.
✔ Good
calculateSalary()
printMenu()
getAverageScore()
❌ Bad
cs()
func1()
doIt()
Why?
Clear names make your code easier to understand for you and others.
✅ 2. Keep Functions Short and Focused
(Single Responsibility)
A function should do one job only.
✔ Good example:
calculateTax(amount) — calculates tax only.
❌ Bad example:
A function that reads input, calculates tax, prints results, updates file…
Why?
Smaller functions are easier to test, debug, and reuse.
✅ 3. Use Parameters Instead of
Hardcoding Values
Avoid writing values inside the function that cannot be changed.
✔ Use function parameters:
double computeDiscount(double price, double rate);
❌ Avoid:
double computeDiscount() { return 100 * 0.10; }
Why?
Parameters make the function flexible and reusable.
✅ 4. Use the Correct Return Type
If your function:
Computes and gives back a result → use int, double, string, etc.
Only performs an action → use void.
✔ Example with return value:
double getArea(double radius);
✔ Example void function:
void displayMessage();
Why?
Choosing the right return type avoids confusion and errors.
✅ 5. Avoid Too Many Parameters
Functions should not take too many arguments.
If you have more than 3–4 parameters, consider using:
a struct
a class
a vector
or grouping related data
Why?
Too many parameters confuse the reader and increase mistakes.
✅ 6. Document the Function
(Comments)
Each function should have a short comment explaining:
What it does
What parameters mean
What it returns
Example:
// Computes the area of a circle.
// radius → radius of the circle.
// returns → area in square units.
double getArea(double radius);
Why?
Comments make your code understandable for future readers (and your future self).
✅ 7. Avoid Using Global Variables
Instead, pass values using parameters.
❌ Avoid:
int x;
int compute() { return x * 2; }
✔ Prefer:
int compute(int value);
``
Why?
Global variables cause bugs and make code harder to track.
✅ 8. Return Values, Don’t Print Them
(Unless Purpose is Printing)
Let your function do calculations and let main() decide whether to print.
❌ Bad:
double add(double a, double b) {
cout << a + b;
}
✔ Good:
double add(double a, double b) {
return a + b;
}
Printing should be done in user-interface functions, not logic functions.
✅ 9. Handle Errors Gracefully
Use exception handling for invalid inputs or impossible calculations.
Example:
double divide(double a, double b) {
if (b == 0) throw invalid_argument("Division by zero!");
return a / b;
}
Why?
Prevents the program from crashing unexpectedly.
✅ 10. Use Inline Functions ONLY for
Small Tasks
✔ Good:
inline int square(int x) { return x * x; }
❌ Bad (too large):
inline void processBankTransactions() {
// long code...
}
Why?
Inline is good for tiny functions—NOT large ones.
⭐ Example Incorporating Best Practices
Real-World Scenario: Compute Delivery Fee
double computeDeliveryFee(double distance, double weight) {
// Calculates delivery fee based on distance and weight.
double fee = distance * 5 + weight * 2;
return fee;
}
✔ Clear name
✔ Uses parameters
✔ No printing inside
✔ Returns result
✔ Easy to reuse
Note
Principle Meaning
Clear Function Name Easy to understand purpose
Single Responsibility One function → one job
Use Parameters Avoid hardcoding values
Correct Return Type Return values or use void
Keep It Short Easier to test & debug
Minimal Parameters Use structs/classes if needed
Comment Functions Improve readability
Avoid Globals Less bugs
Return Values, Don’t Keep logic separate
Print
Use Inline Wisely Only for small functions