Declaring and defining functions
A function has a return type, a name, a parameter list and a body: int add(int a, int b) { return a + b; }. That whole thing is a definition. A declaration (also called a prototype) is just the first line followed by a semicolon: int add(int a, int b);. It promises the compiler "this function exists, with this signature", which is enough to compile a call to it.
The C++ compiler reads a file top to bottom, once. A function must be declared above the first line that calls it. You can either define helper functions above main, or declare them at the top and define them below. A program may declare a function many times but define it only once (the one definition rule).
#include <iostream>
// Declarations: enough for main to call these
double celsiusToF(double c);
void printRow(const char* label, double c);
int main() {
printRow("freezing", 0);
printRow("body", 37);
printRow("boiling", 100);
}
// Definitions: the actual bodies, after main
double celsiusToF(double c) {
return c * 9 / 5 + 32;
}
void printRow(const char* label, double c) { // void: returns nothing
std::cout << label << ": " << c << " C = " << celsiusToF(c) << " F\n";
}freezing: 0 C = 32 F
body: 37 C = 98.6 F
boiling: 100 C = 212 FDelete the two declarations at the top and compile. Then move the definitions above main and it compiles again with no declarations at all.
use of undeclared identifier (calling before declaring)
#include <iostream>
int main() {
std::cout << square(4) << '\n';
}
int square(int x) { return x * x; }main.cpp:4:18: error: use of undeclared identifier 'square'
4 | std::cout << square(4) << '\n';
| ^~~~~~When the compiler reaches line 4 it has not seen square yet; it does not look ahead. Python and JavaScript find functions at runtime, so this surprises people coming from them.
Add a declaration above main (or move the definition up).
#include <iostream>
int square(int x); // declaration
int main() {
std::cout << square(4) << '\n';
}
int square(int x) { return x * x; }