Functions are the building blocks of a well-organized program. Instead of writing one giant "spaghetti" block of code in main(), you break your program into smaller, reusable pieces.
Think of a function like a recipe: you give it ingredients (parameters), it performs steps (logic), and it gives you a result (return value).
1. Anatomy of a Function
Every function needs four things:
Return Type: What kind of data comes out? (
int,double,voidif nothing).Function Name: How do you call it? (e.g.,
calculateTax).Parameters (Inputs): What data does it need to work?
Body: The code inside
{}that does the work.
2. Pass by Value vs. Pass by Reference
Pass by Value: A copy of the variable is sent. The original variable outside the function stays the same.
Pass by Reference (
&): The actual address of the variable is sent. If you change it inside the function, the original variable changes too.
Code Example: Math and Logic Functions
This program uses a function to add numbers and another to "power up" a player by reference.
#include <iostream>
using namespace std;
// 1. A function that RETURNS a value (Pass by Value)
int addNumbers(int a, int b) {
return a + b;
}
// 2. A function that MODIFIES the original (Pass by Reference)
// The '&' symbol means we are touching the actual memory of 'hp'
void powerUp(int &hp) {
hp = hp + 50;
cout << "Healing... HP is now: " << hp << endl;
}
// 3. A 'void' function (does something but returns nothing)
void greetUser(string name) {
cout << "Welcome back, " << name << "!" << endl;
}
int main() {
greetUser("Alex");
// Using the return function
int sum = addNumbers(10, 20);
cout << "The sum is: " << sum << endl;
// Using Pass by Reference
int playerHealth = 10;
cout << "Starting Health: " << playerHealth << endl;
powerUp(playerHealth); // This will change playerHealth to 60
cout << "Health after function call: " << playerHealth << endl;
return 0;
}Why use Functions?
Reusability: Write once, use 100 times.
Readability:
main()looks clean; you just see a list of tasks.Testing: It's easier to fix a bug in one small function than in 1,000 lines of code.