Book Image

Learning C++ by creating games with UE4

By : William Sherif
Book Image

Learning C++ by creating games with UE4

By: William Sherif

Overview of this book

Table of Contents (19 chapters)
Learning C++ by Creating Games with UE4
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
2
Variables and Memory
Index

Writing our own functions


Say, we want to write some code that prints out a strip of road, as shown here:

cout << "*   *" << endl;
cout << "* | *" << endl;
cout << "* | *" << endl;
cout << "*   *" << endl;

Now, say we want to print two strips of road, in a row, or three strips of road. Or, say we want to print any number of strips of road. We will have to repeat the four lines of code that produce the first strip of road once per strip of road we're trying to print.

What if we introduced our own C++ command that allowed us to print a strip of road on being called the command. Here's how that will look:

void printRoad()
{
  cout << "*   *" << endl;
  cout << "* | *" << endl;
  cout << "* | *" << endl;
  cout << "*   *" << endl;
}

This is the definition of a function. A C++ function has the following anatomy:

Using a function is simple: we simply invoke the function we want to execute by name, followed...