A function is a named block of code that does one job. You write it once, give it a name, and then call that name whenever you need the job done.
You already use functions without writing them. When you write cin >> x, sqrt(x) or sort(a, a + n), someone else wrote that code and gave it a name. Now you will learn to write your own.
Real-life analogies
| Analogy | Function idea |
|---|---|
| A coffee machine: you press a button, coffee comes out | You call the function; it runs hidden steps and gives a result |
Imagine you must check whether three numbers are odd and print the answer.
#include <bits/stdc++.h>
using namespace std;
int main() {
int a = 7, b = 10, c = 13;
bool oddA = true;
if (a % 2 == 0) oddA = false;
cout << a << (oddA ? " is odd" : " is even") << "\n";
bool oddB = true;
if (b % 2 == 0) oddB = false;
cout << b << (oddB ? " is odd" : " is even") << "\n";
bool oddC = true;
if (c % 2 == 0) oddC = false;
cout << c << (oddC ? " is odd" : " is even") << "\n";
}
The same 3 lines are copied three times. What goes wrong?
#include <bits/stdc++.h>
using namespace std;
bool isOdd(int n) { // the function definition
if (n % 2 == 1) return true;
else return false;
}
int main() {
int a = 7, b = 10, c = 13;
cout << a << (isOdd(a) ? " is odd" : " is even") << "\n";
cout << b << (isOdd(b) ? " is odd" : " is even") << "\n";
cout << c << (isOdd(c) ? " is odd" : " is even") << "\n";
}
The logic lives in one place. main() now reads almost like English.
| Benefit | Meaning |
|---|---|
| Code Reusability | Write once, call many times |
| Readability | A good name (isOdd) explains the code without comments |
| Organization | Each function has one small job |
| Easier debugging | Test and fix one function at a time |
| Teamwork and contests | You can paste a tested helper into a new solution |
Three different things, often confused:
| Term | What it does | Example |
|---|---|---|
| Declaration (prototype) | Tells the compiler the function exists: name, return type, parameter types | int add(int, int); |
| Definition | Gives the actual body | int add(int x, int y) { return x + y; } |
| Call | Runs the function | add(3, 4) |