Game Development Reference
In-Depth Information
To which
while
-instruction is this
for
-instruction equivalent? For completeness, here
is the syntax diagram of the
for
-instruction:
9.5 A Few Special Cases
9.5.1 No Repeat at All
Sometimes, it can happen that the condition in the header of a
while
-instruction is
already
false
in the beginning. Look at the following code fragment:
int
x=1;
int
y=0;
while
(x < y)
x++;
In this case, the body of the
while
-instruction is not executed, not even once! There-
fore, in this example the variable
x
retains the value 1.
9.5.2 Infinite Repeat
One of the dangers of using
while
-instructions (and to a lesser extent
for
-instructions)
is that they might never end, if you do not take care. We can easily write such an
instruction:
while
(1+1 == 2)
x=x+1;
In this case, the value of
x
is incremented without end. This is because the condition
1+1==2
always yields
true
, no matter what is done in the body of the instruction.
Now this example is quite easy to avoid, but often a
while
-instruction ends in an