Lesson 6
Functions
Short answer: a function is a named block of code with inputs (parameters) and one output (the return value). Call it by name instead of copying its body.
The smallest useful function
#include <iostream>
using namespace std;
int square(int x) {
return x * x;
}
int main() {
cout << square(3) << endl;
cout << square(7) << endl;
return 0;
}
Three parts: return type (int), name (square), parameter list (int x). The body returns a value of that type.
Why bother? Because you stop repeating yourself
Compare two versions of the same program:
#include <iostream>
using namespace std;
bool isEven(int n) {
return n % 2 == 0;
}
int main() {
int count = 0;
for (int i = 1; i <= 10; i++) {
if (isEven(i)) count++;
}
cout << count << " even numbers" << endl;
return 0;
}
Now the definition of "even" lives in exactly one place. If the rule ever changes, you change one line instead of ten. That is the entire argument for functions.
Returning vs printing
A function that returns can be reused in arithmetic; one that prints cannot:
#include <iostream>
using namespace std;
int add(int a, int b) {
return a + b;
}
int main() {
int total = add(2, 3) * 10; // possible: add() gives a value
cout << total << endl;
return 0;
}
Prefer returning. Print at the top level (main), compute in functions.
Functions that call themselves: recursion
The factorial is the textbook case — n! = n × (n−1)!:
#include <iostream>
using namespace std;
long long factorial(int n) {
if (n <= 1) return 1; // base case — without it, infinite recursion
return n * factorial(n - 1);
}
int main() {
cout << factorial(5) << endl; // 120
return 0;
}
Recursion needs a base case that stops the descent. Keep reading: a whole article on recursion, and the practice problems All Permutations and Tower of Hanoi.
The three bugs
- No return on some path. A function declared
intthat can reach the end without returning gives undefined garbage. - Passed by value. Changing a parameter does not change the caller's variable. (The full article.)
- Missing base case in recursion. The program crashes with a stack overflow instead of printing a number.