5.8. Functions¶
In the last section I mentioned “all the things functions are good for.” About this time, you might be wondering what exactly those things are. Here are some of the reasons functions are useful:
By giving a name to a sequence of statements, you make your program easier to read and debug.
Dividing a long program into functions allows you to separate parts of the program, debug them in isolation, and then compose them into a whole.
Functions facilitate both recursion and iteration.
Well-designed functions are often useful for many programs. Once you write and debug one, you can reuse it.
For example, instead of writing the 53 lines of code below...
1#include <iostream>
2using std::cout;
3
4int main() {
5 int x = 4;
6 x = x * 2;
7 x = x / 2;
8 x = x + 2;
9 x = x - 2;
10 cout << x << '\n';
11 x = 13;
12 x = x * 2;
13 x = x / 2;
14 x = x + 2;
15 x = x - 2;
16 cout << x << '\n';
17 x = 100;
18 x = x * 2;
19 x = x / 2;
20 x = x + 2;
21 x = x - 2;
22 cout << x << '\n';
23 x = 22;
24 x = x * 2;
25 x = x / 2;
26 x = x + 2;
27 x = x - 2;
28 cout << x << '\n';
29 x = 220;
30 x = x * 2;
31 x = x / 2;
32 x = x + 2;
33 x = x - 2;
34 cout << x << '\n';
35 x = 0;
36 x = x * 2;
37 x = x / 2;
38 x = x + 2;
39 x = x - 2;
40 cout << x << '\n';
41 x = 1000;
42 x = x * 2;
43 x = x / 2;
44 x = x + 2;
45 x = x - 2;
46 cout << x << '\n';
47 x = 254;
48 x = x * 2;
49 x = x / 2;
50 x = x + 2;
51 x = x - 2;
52 cout << x << '\n';
53}
A function allows you to reduce it to the 21 lines of code below. The function makes it easier to read, debug, and use the function many times without rewriting it each time.
1#include <iostream>
2
3void all_operators(int x) {
4 x = x * 2;
5 x = x / 2;
6 x = x + 2;
7 x = x - 2;
8 std::cout << x << '\n';
9}
10
11int main() {
12 all_operators(4);
13 all_operators(13);
14 all_operators(100);
15 all_operators(22);
16 all_operators(220);
17 all_operators(0);
18 all_operators(1000);
19 all_operators(254);
20}
Q1
What is a function in C++?
Q2
Create a function called absolute_value, which returns the absolute value of a parameter num. Assume you do not have access to #include <cmath>.
-
return abs_num; } } -
return num; } -
else { -
if (num > 0) { -
int abs_num = -(num); -
int absolute_value (int num) #distractor -
int absolute_value (int num) { -
void absolute_value (int num) #distractor -
void absolute_value (int num) { #distractor
Q3
What is of these is NOT a reason that functions are useful?
More to Explore
From cppreference.com