Defining Functions
In this lesson, you will learn to write your own functions. Let's start with a problem: we need the areas of three rectangles. The area of a rectangle is its width times its height, so we could write the program you have in the editor:
#include <iostream>
int main() {
int width1 = 5;
int height1 = 6;
int area1 = width1 * height1;
std::cout << area1 << std::endl;
int width2 = 10;
int height2 = 5;
int area2 = width2 * height2;
std::cout << area2 << std::endl;
int width3 = 1;
int height3 = 5;
int area3 = width3 * height3;
std::cout << area3 << std::endl;
}Run it. It prints:
30
50
5It works, but we wrote the same four lines three times, and only the numbers changed. Imagine a hundred rectangles! And if we found a mistake in the calculation, we would have to fix it in a hundred places.
Programmers try not to repeat code. Instead, they write the repeated part once, give it a name and then use it wherever they need it. Such a named piece of code is called a function.
In fact, you have been writing one function since the first lesson: main. The line int main() { starts the definition of a function named main, and the statements between the curly braces are its body. When you run a program, it starts by running the function main. You define your own function in a similar way:
void sayHello() {
std::cout << "Hello!" << std::endl;
std::cout << "Have a nice day!" << std::endl;
}A function definition has these parts:
void(English for empty) is the return type. It says that the function doesn't return any value; it only does something, here it prints two lines. You will meet functions that return values later in this lesson.- The name of the function, here
sayHello. It follows the same rules as variable names: letters, digits and_, no spaces, upper and lower case matter, and names made of several words are written in camelCase. Choose a name that says what the function does, such assayHelloorprintArea. - Parentheses
(). They are empty for now; you will soon find out what goes in them. - The body of the function in curly braces
{ }. It holds the statements the function runs.
Write the function above main, not inside it. In C++, a function definition can't be inside another function. If you write it in the body of main, the program doesn't compile, and the compiler reports the error error: function definition is not allowed here.
When you run the program with the new function, it still prints only what main prints. That's not a mistake! A definition only says what the function should do, like a recipe written down in a cookbook: nobody has cooked anything yet. In the next exercise, you will make the function run.
Instructions
- 1
Above the function
main, in place of the comment, create a function namedfirstFunctionwhose body printsThis is my first function!. Then run the program: it still prints only the three areas, because nobody has called the function yet. That's how it should be.