C++, lesson 6
A function packages a piece of work under a name. Instead of repeating the same lines, you call the function, and instead of reading twenty lines you read one well-chosen name.
The signature says what goes in and what comes out: double is the return type, and
(double radius) is the parameter list. return sends a value back and ends the function.
A function that returns nothing has return type void.
A function must be declared before it is called. Either define it above main, or put a
declaration (the signature plus ;) near the top and the full definition anywhere below.
(): the function gets its own copy. Changing it doesn't affect the caller. Use it for small, cheap types like , , , .
2 exercises to try what you just read.
int nintdoublecharboolBy reference (int& n): the parameter is another name for the caller's variable.
Changing it changes the original. Use it when the function's job is to modify the caller's data.
By const reference (const std::string& s): no copy is made, and the compiler forbids
changes. Use it for larger types you only read, such as strings and vectors. Copying a long
string just to look at it wastes time.
A reference must be bound to a variable when it's created, and it stays bound to that variable for life. Never return a reference to a local variable: the local is destroyed when the function ends, leaving a dangling reference.
Several functions can share a name if their parameter lists differ. The compiler picks the one that matches the arguments:
Trailing parameters can have default values that are used when the caller leaves them out:
Once a parameter has a default, every parameter after it needs one too.
Variables declared inside a function (or any { } block) are local: they exist only
inside it, and each call gets fresh ones. Two functions can each have a local total without
any conflict. Prefer passing data in through parameters and out through return values over
sharing global variables.
Write void sort3(int& a, int& b, int& c) that rearranges its three arguments so that
a >= b >= c. A helper void swap_if_less(int& x, int& y) that swaps when x < y makes this
short. Read three race scores, call sort3, and print the podium.
Write double postage(double kg, bool express = false):
$4.00 for parcels up to 1 kg, plus $1.50 for every started kilogram
above 1 (so 1.2 kg costs 5.50 and 3 kg costs 7.00)Each input line has a weight and an optional word express. Read lines until the input ends;
call postage(kg) for normal lines and postage(kg, true) for express ones. Print each price
with two decimals.
Read each line with std::getline, then pull the fields out with an std::istringstream
(from <sstream>), exactly like reading from std::cin. std::ceil from <cmath> rounds up.
double circle_area(double radius) {
constexpr double pi{3.141592653589793};
return pi * radius * radius;
}
int main() {
std::cout << circle_area(2.0) << '\n'; // 12.5664
}void add_bonus(int& score, int bonus) {
score += bonus;
}
int points{10};
add_bonus(points, 5); // points is now 15int count_vowels(const std::string& text) {
int count{0};
for (char c : text) {
if (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u') {
++count;
}
}
return count;
}int largest(int a, int b) { return a > b ? a : b; }
double largest(double a, double b) { return a > b ? a : b; }std::string greet(const std::string& name, const std::string& greeting = "Hello") {
return greeting + ", " + name + "!";
}
greet("Ada"); // "Hello, Ada!"
greet("Ada", "Hi"); // "Hi, Ada!"Input:
71 93 85
Output:
Gold: 93
Silver: 85
Bronze: 71Input:
0.5
1.2 express
3
Output:
4.00
11.00
7.00