Game Development Reference
In-Depth Information
Chapter 5
Functions, the Building Blocks
of C++
Modern games consist of hundreds of thousands of lines of code and can be worked on by teams
consisting of hundreds of people. C++ provides the ability to separate code into blocks called
functions to allow us to build more modular programs.
A function allows us to write a routine that can be reused throughout our program. The benefits of
this are significant. You saw this in the last chapter when we looked at some of the C++ functions
for working with strings. We did not have to write our own code to determine if two strings were the
same; instead, we could simply pass them both into a function and the return value told us the result
of the function.
This chapter covers how we write functions, including how to pass values to a function, how to pass
pointers to functions, and a special type of pointer, the reference.
Writing Our First Function
A C++ compiler requires that functions are declared and defined before they can be used, just as
with variables. It's also possible to define and declare a function at the same time. Listing 5-1 shows
the code for a simple program that calls a single function.
Listing 5-1. Our First Function
#include <iostream>
using namespace std;
void PrintHello()
{
cout << "Hello!" << endl;
}
49
 
Search WWH ::




Custom Search