Learn C++ · lesson 22 of 61 · about 8 minutes
Defining Functions
Move the adventure's health bar into a function, so it can be drawn again whenever the health changes.
What you'll learn
- Define a function
- Pass arguments to parameters
- Return a value
The same bar, twice
The spikes in the corridor cost health, so the bar drawn before them is out of date by the bridge. Copying the eight lines of the bar loop would work, but then a change to the bar has to be made twice. A function puts those lines in one place with a name, healthBar, and any part of the adventure can call it.
Reusable code
int area(int w, int h) { return w * h; } defines a function that takes two ints and returns an int. void means it returns nothing.
A function must be declared before it's called. Either define it above main, or write a declaration (int area(int w, int h);) at the top.
Functions with and without results
#include <iostream>
#include <string>
int area(int w, int h) {
return w * h;
}
void greet(const std::string& name) {
std::cout << "Hi, " << name << "!\n";
}
int main() {
greet("Phoebe");
std::cout << area(4, 3) << "\n";
std::cout << area(2, 2) + area(1, 5) << "\n";
}Output
Hi, Phoebe!
12
9Step through a call: into the function and back
#include <iostream>
int square(int x) {
return x * x;
}
int main() {
int a = square(3);
std::cout << a + 1 << "\n";
}Output
10The bar as a function
#include <iostream>
#include <string>
// the health bar: ten characters, one # for every 10 health
std::string healthBar(int health) {
std::string bar;
for (int i = 0; i < 10; i++) {
if (i < health / 10) {
bar += '#';
} else {
bar += '-';
}
}
return bar;
}
int main() {
std::cout << "HP [" << healthBar(75) << "]\n";
std::cout << "HP [" << healthBar(100) << "]\n";
}Output
HP [#######---]
HP [##########]Tip
const std::string& is the usual way to pass text into a function: no copy is made, and the function promises not to change it. You'll learn exactly why in the References lesson.
Now try it yourself
This lesson is free in Codiqo, with 8 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.