Page 1 of 1

while() function

PostPosted: Wed Apr 04, 2012 8:17 pm
by Hblade
How does this function work?

Code: Select all
while(var)
{
?
}

Re: while() function

PostPosted: Wed Apr 04, 2012 8:27 pm
by skydereign
It's a loop mechanism.
Code: Select all
while(condition is true)
{
    // do something
}

So if you wanted to simulate a for loop you could do it like this.
Code: Select all
int i=0;
while(i<10)
{
    // do something
    i++;
}

Just make sure the while loop is escapable. There is also do while, which runs the code first, and then checks if it needs to loop.
Code: Select all
do
{
    // do something
}while(condition);
// notice, you need the semicolon after this while (but not the other)

Re: while() function

PostPosted: Wed Apr 04, 2012 8:30 pm
by Game A Gogo
there are two varients. The normal while

Code: Select all
while(Conditional Statement)
{
    do things here while the Conditional Statement is true
}


and the do-while

Code: Select all
do
{
    do things here
}while(Conditional Statement)


The first while loop will ONLY run if Conditional Statement is true, but if the condition is not met, the code won't get run at all.
If the Conditional Statement is true, then the code will keep on running until the Condition Statement returns false.

The do-while loop is the same thing, except that the code will get run at least once!

EDIT:
Aww, sky beat me to it xP

Re: while() function

PostPosted: Wed Apr 04, 2012 8:37 pm
by Hblade
Thanks guys :) now does this happen all in 1 frame, like using for(i=0;ect..)?

Re: while() function

PostPosted: Wed Apr 04, 2012 8:40 pm
by skydereign
Yeah. Any code in any event must finish before the game can move on. So, if you had an infinite while loop, the game would freeze.

Re: while() function

PostPosted: Thu Apr 05, 2012 4:10 am
by Hblade
Oh I see. Thanks :3