Course Content
Introduction to C++
Functions are small subroutines that can be called when needed. Each function has a name which it can be called.
Note
The name
"main"
is already reserved by the C++ language. Therefore, when declaring a function with this name, the compiler will generate an error.
To create a function is enough:
- specify the type of data it will return;
- give her a name;
- write a block of instructions
“{…}”
(or body of function).
For example, let's create a function that outputs the text "c<>definity"
:
Now we can call our new function:
main.cpp
Let's write the real function: At the university, you constantly need to convert degrees Fahrenheit to degrees Celsius, let's write a function that will do this instead of us.
main.cpp
Note
int degree
is the function`s argument. In fact, this is the information with which the function will work, in our case, these are degrees Fahrenheit, which need to be converted to degrees Celsius. Arguments will be discussed in more detail later.
The compiler reads our program code from top to bottom, just like a human reads the page of a book. If the compiler detects unfamiliar variable/function names, it will generate an error.
For example, let's try to call a function before it is created:
This example throws an error. This is done on purpose.
main.cpp
For such cases, you need to use the function prototype.
The idea behind prototyping is to warn the compiler about our function ahead of time. Creating a prototype looks the same as a regular function declaration, but with a nuance:
- specify the type of the future function;
- give it a name;
- arguments (if needed);
- put the character of the end of the expression
;
.
Let's add a function prototype to our example that was throwing an error:
main.cpp
Note
Prototyping is useful when you are working with a lot of features. To avoid "garbage" in the main file, prototypes and function definitions are moved to third-party files and included in the main file with the
#include
directive.
What the name of this function?
Select the correct answer
Section 5.
Chapter 1