Game Development Reference
In-Depth Information
{
char* cStyleString = "CStyleString";
cout << cStyleString << endl;
return 0;
}
The value
"CStyleString"
in quotes is known as a
string literal
. The compiler creates a table of all of
the string literals in our program and stores them together in memory. We can access these string
literals by assigning them to a
char*
. When we use
cout
with a
char*
that stores the address of a
string literal it will print out the entire string and then stop.
C++ achieves this by adding an extra character to the end of C style strings, the null terminator. We
can see this in action using the code in Listing 4-6.
Listing 4-6. The NULL Terminator
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
char* cStyleString = "CStyleString";
cout << (cStyleString[12] == '\0') << endl;
return 0;
}
This program will print out a 1 as the 13th character of our string matches the null terminator
character,
\0
. As you can see, we can store the address of the string into a
char*
, and we can then
access individual characters using either pointer arithmetic or array indexing.
Note
Characters by default in C++ programs (and in this topic) all use the American Standard Code for
Information Interchange (ASCII) encoding. ASCII characters can be represented using single quotes such as
'a'
. The null terminator is a special character and as such must be preceded by a \,
'\0'
using
'0'
would
represent the number zero and not the null terminator character. The actual decimal value of
'a'
is 87,
'0'