Game Development Reference
In-Depth Information
Another type of while loop is the do...while loop. Listing 6-8 shows an example of this type.
Listing 6-8. A do...while Loop
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
unsigned int array[10];
unsigned int count = 0;
do
{
array[count] = count * 2;
cout << "Loop Iteration: " << array[count++] << endl;
} while (count < 10);
return 0;
}
The main difference between these two types of loop is that the do...while version will always
execute at least once. The test occurs at the end of the first iteration of the do...while whereas
the test occurs at the beginning of a standard while loop.
If count in Listing 6-7 had been initialized to 10, the loop would never have run, whereas in
Listing 6-8 it would have run once (and caused an array overrun).
There are also times when we are programming when we want to execute specific code for a given
value contained in a variable. C++ provides the switch statement for these moments.
The switch Statement
A switch statement can be used in place of an if...else if block when we have a set of literal
values that we wish to differentiate between. Listing 6-9 shows an example using an enum .
Listing 6-9. The switch Statement
#include <iostream>
using namespace std;
int main(int argc, const char * argv[])
{
enum class Colors
{
Red,
Green,
Blue
};
 
Search WWH ::




Custom Search