Functions in C++
Build your own reusable blocks of code
Big Idea: A function is a named block of code that does one job. You write it once, give it a name, and then call it as many times as you like. Functions keep your programs short, tidy, and easy to fix.
By the end you will be able to:
- declare and define a function,
- pass parameters by value and by reference,
- return a value (or return nothing with
void), - write overloaded functions that share a name.
1. What is a function?
Think of a function like a kitchen appliance. A blender has a name ("blender"), you put things in (fruit), it does its job, and something comes out (a smoothie). You do not rebuild the blender every time — you just use it again.
A function is the same: you give it a name, it can take some inputs (called parameters), it runs its steps, and it can hand back a result (the return value).
2. Declare vs. define
There are two related ideas:
- A declaration (also called a prototype) tells the compiler the function's name, what it returns, and what parameters it takes. It ends with a semicolon and has no body.
- A definition is the real thing: the same header plus the body in
{ }that does the work.
#include <iostream>
using namespace std;
// Declaration (prototype): promises the function exists.
int add(int a, int b);
int main() {
cout << add(3, 4) << endl; // we can call add here
return 0;
}
// Definition: the real body that does the work.
int add(int a, int b) {
return a + b;
}
Expected output:
7
The declaration lets
main call add even though the full definition appears lower in the file.