C++ Tutorial
C++ Functions
A function has a return type, a name, and a body. Call it to reuse work without copy-paste.
A named piece of work
You already use functions: main is one, and swapInts in the references chapter was another. A function packages a block of statements behind a name. You write the steps once. You call the name whenever you need those steps.
Every function has a return type (what it hands back, or void if it hands back nothing), a name, parentheses, and a brace body. Execution of a program still starts at main. Other functions run only when something calls them.
Return a value
Put helpers above main so the compiler has already seen the full definition whenmain calls them. The return type on the left must match what return sends back.
Example
#include <iostream>
using namespace std;
double square(double x) {
return x * x;
}
int main() {
cout << square(3.0) << endl;
double area = square(5.0);
cout << area << endl;
return 0;
}square(3.0) is a call. The argument 3.0 becomes the parameter x inside the function. When return runs, the call is replaced by the value 9.0. You can print that value or store it.
void means no value back
A void function does work — usually printing or updating something through a reference — and then stops. There is no return value to assign. You can write a bare return; to leave early. You cannot write int n = greet();.
Example
#include <iostream>
#include <string>
using namespace std;
void greet(string name) {
cout << "hello, " << name << endl;
}
int main() {
greet("Mina");
greet("Omar");
return 0;
}Two calls, one definition. Change the message in greet and every call site updates. That is the whole reason to extract a function: one place to fix, not six pasted copies.
Declaration versus definition
A definition is the function with a body. A declaration (a prototype) is the return type, the name, and the parameter list, ending with a semicolon and no braces. The compiler only needs a declaration before the first call. The definition can sit later in the file.
Example
#include <iostream>
using namespace std;
int maxOf(int a, int b);
int main() {
cout << maxOf(4, 9) << endl;
cout << maxOf(12, 3) << endl;
return 0;
}
int maxOf(int a, int b) {
if (a > b) {
return a;
}
return b;
}The prototype above main promises that maxOf exists. The definition belowmain keeps the file readable when helpers grow. The parameter names in the prototype are optional; the types are not. They must match the definition.
Call order and one main
C++ reads the file top to bottom. If you call a function the compiler has never seen, you get an error. Two legal layouts:
- Define helpers first, then
main. - Declare prototypes first, then
main, then define the helpers.
A program you run has exactly one main. Helpers return to whoever called them. mainreturns to the operating system. Keep using return 0; at the end of main.
The return type is not optional. If you forget it, g++ will not accept the function. void is the type that means “returns nothing”.
What belongs in a function
Give a function one job and a name that says that job: square, greet,maxOf. If you cannot name it without the word “and”, it is probably two functions. Do not put all of main into one giant helper. Leave program setup in main and factor the repeated pieces.
Example
#include <iostream>
using namespace std;
int square(int n) {
return n * n;
}
int cube(int n) {
return n * n * n;
}
int main() {
for (int i = 1; i <= 4; i++) {
cout << i << " squared " << square(i)
<< ", cubed " << cube(i) << endl;
}
return 0;
}Next: how arguments get into the function — copy, share, and default values.
Worked examples
The short listings above are there so you can see the grammar. The programs here use the same statements on quantities that already have units: a speed, a pH, a count of bases. They are classroom numbers. Air resistance is ignored. g is 9.81 m/s² unless a line says otherwise.
Open them in the C++ editor at /cpp/try. Change one measurement and check whether the result still has the right unit.
Physics
Kinetic energy as a function
Once you have written ½ m v² twice, it should be a function. 2 kg at 3 m/s is 9 J. Call the same function for a 0.05 kg dart and you cannot paste the 2 and the 3 by accident.
KE = ½ m v²
Example
#include <iostream>
using namespace std;
double kinetic_energy(double mass, double speed) {
return 0.5 * mass * speed * speed;
}
int main() {
cout << "KE = " << kinetic_energy(2.0, 3.0) << " J" << endl;
return 0;
}Maths
Area of a circle
A = πr². For r = 2, A ≈ 12.566. The function is the formula from the exam paper. Change r in main; do not copy the π line again.
A = π r²
Example
#include <iostream>
using namespace std;
double circle_area(double r) {
const double PI = 3.14159;
return PI * r * r;
}
int main() {
cout << "A = " << circle_area(2.0) << endl;
return 0;
}