Game Development Reference
In-Depth Information
Using static to Alter Global Scope
The last use of the static keyword allows you to tell the compiler that you would like a variable to
exist within the scope of a single file rather than in the global scope. Global variables are generally
frowned on as they break encapsulation in object-oriented programs and we won't be using any in
our Text Adventure game that hold game data. You might come across these in production code,
though, so it's good to know how to work with them. Listing 9-8 shows an example of a globally
scoped and a file scoped variable.
Listing 9-8. Globally Scoped and File Scoped Variables
#include "stdafx.h"
#include <iostream>
#include "extern.h"
int globalVariable = 0;
static int fileVariable = 0;
int _tmain(int argc, _TCHAR* argv[])
{
IncrementGlobalCounters();
std::cout << globalVariable << std::endl;
return 0;
}
Listing 9-8 defines a global variable named globalVariable and a file variable named fileVariable .
The declaration of the function IncrementGlobalCounters is contained in the extern.h header file.
Listing 9-9 shows the contents of this basic file.
Listing 9-9. extern.h
#pragma once
void IncrementGlobalCounters();
The function definition is in extern.cpp , shown in Listing 9-10.
Listing 9-10. extern.cpp
#include "extern.h"
void IncrementGlobalCounters()
{
extern int globalVariable;
++globalVariable;
// Error - will not compile as fileVariable is not global!
extern int fileVariable;
++fileVariable;
}
 
Search WWH ::




Custom Search