Show contents
Chapter 1 of 7 · 20 min
Functions and references
By the end of this chapter, you'll be able to
- Define and call a function with parameters and a return value
- Tell pass-by-value and pass-by-reference apart
- Pass large objects by const reference
- Use default parameters and function overloading
Defining a function
#include <iostream>
double discounted_price(double price, double percent) {
return price * (1 - percent / 100);
}
int main() {
std::cout << discounted_price(80, 25) << "\n";
std::cout << discounted_price(19.99, 10) << "\n";
return 0;
}
60
17.991
- The return type (
double) comes before the name;voidmeans the function returns nothing. - The parameters are typed. When calling, the arguments are matched with the parameters in order.
returnsends back the result and ends the function.- As in C, the compiler reads from top to bottom: a function must be declared before it's called, either by defining it higher up, or with a prototype (
double discounted_price(double price, double percent);).
Value or reference?
By default, an argument is copied into the parameter (pass-by-value): the function can't touch the original. By adding & to the parameter's type, you pass by reference: the parameter becomes another name for the caller's variable.
score really is 150.
Text description of the animation
- Two almost identical functions. Only the & differs.
- score is 100.
- bonus_copy receives a copy, 100, and turns it into 150.
- Back in main, the copy has disappeared: score is still 100.
- bonus_ref receives a reference: points is another name for score. Adding 50 to points means adding 50 to score.
- score really is 150.
Three ways to pass a parameter, to choose depending on what the function does with it:
| Parameter | Copied? | Can be changed? | When to use it |
|---|---|---|---|
int n | yes | no (only the copy) | small types: int, double, char, bool |
int& n | no | yes | the function must change the caller's variable |
const std::string& s | no | no | large read-only objects: texts, vectors |
The const reference is the most common for std::strings and std::vectors: no copy (fast), and the guarantee that the function won't change them.
#include <iostream>
#include <string>
#include <vector>
double average(const std::vector<double>& grades) {
double sum = 0;
for (double g : grades) {
sum += g;
}
return grades.empty() ? 0 : sum / grades.size();
}
void greet(const std::string& name, const std::string& greeting = "Hello") {
std::cout << greeting << ", " << name << "!\n";
}
int main() {
std::vector<double> grades = {12, 15.5, 17};
std::cout << "Average: " << average(grades) << "\n";
greet("Thandiwe");
greet("Ravi", "Namaste");
return 0;
}
Average: 14.8333
Hello, Thandiwe!
Namaste, Ravi!
condition ? a : bis the ternary operator: it's worthaif the condition is true,botherwise.= "Hello"is a default parameter: you can leave it out when calling. Default parameters go at the end.
Overloading
Two functions can have the same name if their parameters differ. The compiler picks the right one from the arguments: this is overloading.
#include <iostream>
int area(int side) { return side * side; }
int area(int width, int height) { return width * height; }
double area(double radius) { return 3.14159 * radius * radius; }
int main() {
std::cout << area(4) << " " << area(3, 5) << " " << area(2.0) << "\n";
return 0;
}
16 15 12.5664
Your turn
Worked exercise
Worked exercise: capping a list of grades
Write a function void cap(std::vector<double>& grades, double maximum) that replaces each grade above maximum with maximum, and a function int pass_count(const std::vector<double>& grades) that counts the grades of at least 10. With {8, 21, 14, 25, 10} and a maximum of 20, the program must display 8 20 14 20 10 / passed: 4.
Hint 1
cap, go through with for (double& g : grades) so you can change each item.Hint 2
pass_count changes nothing: a const reference is enough, and a loop with a counter does the rest.Show the solution and common mistakes
#include <iostream>
#include <vector>
void cap(std::vector<double>& grades, double maximum) {
for (double& g : grades) {
if (g > maximum) {
g = maximum;
}
}
}
int pass_count(const std::vector<double>& grades) {
int passed = 0;
for (double g : grades) {
if (g >= 10) {
passed++;
}
}
return passed;
}
int main() {
std::vector<double> grades = {8, 21, 14, 25, 10};
cap(grades, 20);
for (double g : grades) {
std::cout << g << " ";
}
std::cout << "/ passed: " << pass_count(grades) << "\n";
return 0;
}
8 20 14 20 10 / passed: 4
Common mistakes:
- Writing
for (double g : grades)incap: you change copies, and the vector stays the same. - Declaring
pass_count(std::vector<double>& grades)withoutconst: it works, but nothing guarantees the function won't change the grades, and you could no longer call it on a constant vector.
Summary
- 1A function has a return type, a name and typed parameters; void returns nothing.
- 2By value (T x), the function works on a copy; by reference (T& x), on the original.
- 3const T& avoids copying large objects while forbidding changes to them.
- 4Default parameters go at the end; overloading allows several functions with the same name.
- 5A forgotten & causes no error: the program silently changes a copy.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.