6.5 — Declare before you use
Read one box at a time. No rush.
Order matters#
C++ reads your file from top to bottom. If you call a function before it has been seen, you get an error.
C++ — wrong ✗
int main(){ std::cout << add(2, 3); // error: what is add? return 0;} int add(int a, int b){ return a + b;}Fix 1: put it above#
Move add above main. Simple!
Fix 2: a forward declaration#
Or tell C++ "this function exists, details later" with a forward declaration. It is just the first line, with a ;:
C++ — right ✓▶ Run
int add(int a, int b); // forward declaration int main(){ std::cout << add(2, 3); // fine now return 0;} int add(int a, int b){ return a + b;}Declaration vs definition
A declaration says a thing exists (its name and type). A definition also includes the body — the actual steps.
Tip: press ← / → to move between lessons, / to search.