Game Development Reference
In-Depth Information
Listing 4-1. C++ int Array
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int intArray[5] = { 0, 1, 2, 3, 4 };
cout << intArray[0] << endl;
cout << intArray[1] << endl;
cout << intArray[2] << endl;
cout << intArray[3] << endl;
cout << intArray[4] << endl;
return 0;
}
The array operator [] is used to specify an index into an array. The index is a value that specifies
the offset of the variable that we would like to access. A common misunderstanding in computer
programming is the fallacy that programmers “count” from zero. This is not strictly the case;
programmers offset from zero and indexing into arrays is a perfect example of this.
The index 0 specifies that we would like the first element from the array and the index 1 specifies
that we would like the second element. Listing 4-1 supplied indexes to the array using hard-coded
literal values. You can also index into an array using a variable. Listing 4-2 gives an example of this.
Listing 4-2. A Variable Array Index
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int intArray[5] = { 5, 6, 7, 8, 9 };
unsigned int index = 0;
cout << "Index: " << index << endl;
cout << "Value: " << intArray[index++] << endl;
cout << "Index: " << index << endl;
cout << "Value: " << intArray[index++] << endl;
cout << "Index: " << index << endl;
cout << "Value: " << intArray[index++] << endl;
cout << "Index: " << index << endl;
cout << "Value: " << intArray[index++] << endl;
cout << "Index: " << index << endl;
cout << "Value: " << intArray[index++] << endl;
return 0;
}
Search WWH ::




Custom Search