Quiz
Warm-up from lesson 3-3: in `for (int i = 0; i < n; i++)`, where does the variable i exist?
Functions exist so that logic is written once, given a name, tested once, and reused — without them every repeated computation is a copy-paste waiting to drift out of sync. In interviews they are also how you show structure to the person watching you code. C++ adds something Python does not have: the compiler enforces a typed contract on every function boundary.
A function is typed on both ends
Python:
def square(x): return x * x
C++:
int square(int x) { return x * x; }
The first int is the return type, the type of the value the function gives back. Each parameter also declares its type. A function that returns nothing uses the return type void.
void greet(std::string name) { std::cout << "Hi, " << name << "\n"; }
The compiler checks every call against this signature: square("hi") fails to compile, and using square(3) where a string is needed fails too. Your function contracts are enforced the same way variable types were in lesson 1-3.
Declare before use: prototypes
The compiler reads your file top to bottom. If main calls square before the compiler has seen square, the build fails. Two fixes:
- Define functions above
main(fine for small programs). - Put a prototype (the signature followed by a semicolon) at the top, and define the body anywhere:
int square(int x); // prototype: promises this function exists int main() { std::cout << square(6) << "\n"; return 0; } int square(int x) { // definition, after main is fine now return x * x; }
Headers like <iostream> are essentially big collections of prototypes, which is why #include makes std::cout usable.
Code exercise · cpp
Run this two-function program. Note the prototype at the top letting main call cube before its definition.
Code exercise · cpp
Your turn. Write a function `bool is_even(int n)` (recall n % 2 from lesson 3-1) and use it in main to print `even` or `odd` for the input. Input is 7.