In the tutorials so far in this course, you've used functions many times. In this tutorial, you'll see how to create new ones!
Your own functions!
Remember functions like length() that you can execute in C++? Well, good news – you will learn how to write your own functions now!
A function is a sequence of instructions that C++ should execute. As an example, let's define a function that just prints a line of text, and call it from the main function.
type=codeblock|id=cpp_function|autocreate=cppvoid greet() {cout << "Hi there!" << endl;}int main() {greet();return 0;}
Okay, our first function is ready!
In lines 1-3, we define the function. That is, we are telling C++ what should happen when this function is called. In lines 5-8, we have our standard main() function. But notice that in line 6, we are calling function greet() that we defined earlier.
Note: C++ compiles the file from top to bottom. When C++ sees a function call, if it hasn't yet found the function definition, it will throw an error. Hence, we define the function before calling it.
When you run the code above, it produces the following output:
Hi there!
As always, C++ execution starts at the beginning of the main() function. The main function just calls the greet() function. When the function is called, C++ goes and executes the function. Hence, it outputs Hi there!.