C++ Functions
A function is a named block of code that performs one task. You write it once and call it as often as you like. Functions are the main tool for breaking a large program into small, understandable, reusable pieces. You have already used one: main.
Defining and calling a function
#include <iostream>
using namespace std;
void sayHello() {
cout << "Hello from a function!\n";
}
int main() {
sayHello();
sayHello();
cout << "Back in main\n";
}Hello from a function!
Hello from a function!
Back in main
A function definition has four parts:
| Part | In the example | Meaning |
|---|---|---|
| Return type | void |
the type of value it gives back (void = nothing) |
| Name | sayHello |
how you call it |
| Parameter list | () |
input values (none here) |
| Body | { ... } |
the code that runs |
Returning a value
A function with a non-void return type sends a value back to the caller with return. The call expression then becomes that value:
#include <iostream>
using namespace std;
double celsiusToFahrenheit(double c) {
return c * 9.0 / 5.0 + 32.0;
}
int square(int n) {
return n * n;
}
int main() {
cout << celsiusToFahrenheit(25) << "\n";
cout << square(7) + square(3) << "\n";
int s = square(square(2)); // calls can be nested
cout << s << "\n";
}77
58
16
return also ends the function immediately. A void function can use a bare return; to leave early.
Declaration before use
The compiler reads your file from top to bottom, so a function must be declared before it is called. If you prefer main at the top, write a prototype (a declaration ending in ;) first and the full definition later:
#include <iostream>
using namespace std;
// declarations (prototypes)
int maxOfThree(int a, int b, int c);
void printLine(int width);
int main() {
printLine(10);
cout << "Max: " << maxOfThree(4, 11, 7) << "\n";
printLine(10);
}
// definitions
int maxOfThree(int a, int b, int c) {
int m = a;
if (b > m) m = b;
if (c > m) m = c;
return m;
}
void printLine(int width) {
for (int i = 0; i < width; i++) cout << '-';
cout << '\n';
}----------
Max: 11
----------
In larger projects the declarations go into a header file (.h / .hpp) and the definitions into a .cpp file, so other files can #include the header and call the functions.
Breaking a problem into functions
Good functions do one thing and have a name that says what. Here a small report is built from three helpers:
#include <iostream>
using namespace std;
bool isPrime(int n) {
if (n < 2) return false;
for (int d = 2; d * d <= n; d++) {
if (n % d == 0) return false;
}
return true;
}
int countPrimesUpTo(int limit) {
int count = 0;
for (int i = 2; i <= limit; i++) {
if (isPrime(i)) count++;
}
return count;
}
void report(int limit) {
cout << "There are " << countPrimesUpTo(limit) << " primes up to " << limit << "\n";
}
int main() {
report(10);
report(100);
report(1000);
}There are 4 primes up to 10
There are 25 primes up to 100
There are 168 primes up to 1000
Tip: If you find yourself copying and pasting a block of code, it probably wants to be a function. A function name is also documentation:
isPrime(n)explains itself; the loop inside it does not.
Test yourself
What does the return type void mean?
- The function returns 0
- The function returns nothing
- The function can return any type
- The function cannot be called
Your function is defined below main but called inside it. What do you need?
- Nothing
- A prototype before main
- The keyword
extern - To make it
static
What happens to code after a return statement in the same block?
- It runs afterwards
- It is skipped
- It runs only in void functions
- Compile error