If vs. While

Started by
22 comments, last by Tom Sloper 12 years, 9 months ago
I have been teaching myself programming off and on for a few years now, and I am beyond beginner status in many ways, but I seemed to have missed something very important in my teaching.

What is the benefit of using if conditionals instead of while? What I mean to say is, what is the difference, beyond the ability to use multiple break conditions in while statements? I always use if, but a great deal of example code I find, especially in scripting, uses while commands. Can someone explain to me the pros and cons? I am doing really well in my scripting, I have made some advanced scripts for my game betas and demos, but I need to know this. I have implemented both types of conditionals, but I really want to know the nuances of the variations. Thank you guys! (and gals).
Advertisement
The difference is that the 'while' is a loop; it will repeat as long as its condition stays true.

A while loop is equivalent to this:


start:

if (condition)
{
// the contents of the while block would go here.
// any 'break' statements are the same as 'goto end;'

goto start;
}

end:



I have been teaching myself programming off and on for a few years now, and I am beyond beginner status in many ways, but I seemed to have missed something very important in my teaching.

What is the benefit of using if conditionals instead of while? What I mean to say is, what is the difference, beyond the ability to use multiple break conditions in while statements? I always use if, but a great deal of example code I find, especially in scripting, uses while commands. Can someone explain to me the pros and cons? I am doing really well in my scripting, I have made some advanced scripts for my game betas and demos, but I need to know this. I have implemented both types of conditionals, but I really want to know the nuances of the variations. Thank you guys! (and gals).


while is a loop with a conditional in it
int x=0;
while (x<10) {
std::cout << x;
++x;
}
this will print 0123456789

int x=0;
if (x<10) {
std::cout << x;
++x;
}
this will print 0 (its not a loop)

the while loop could be thought of as:

int x=0;
:loop_start
if (x<10) {
std::cout << x;
++x;
goto loop_start;
}

edit: Nypren beat me to it.
[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

I have been teaching myself programming off and on for a few years now, and I am beyond beginner status in many ways, but I seemed to have missed something very important in my teaching.

What is the benefit of using if conditionals instead of while? What I mean to say is, what is the difference, beyond the ability to use multiple break conditions in while statements? I always use if, but a great deal of example code I find, especially in scripting, uses while commands. Can someone explain to me the pros and cons? I am doing really well in my scripting, I have made some advanced scripts for my game betas and demos, but I need to know this. I have implemented both types of conditionals, but I really want to know the nuances of the variations. Thank you guys! (and gals).


i have no idea how you would program something without knowing the difference between the two if you ever used while...

It's pretty simple to understand the difference if you just say it in english...

If something equals something then do something

While something equals something do something.

Let's imagine you want to wash a car using a machine that can only run for 1 minute and it takes an unknown amount of time to wash the entire care and you can only use one line of code to state that you want the entire car cleaned...

If (car == dirty) {CleanCar()}

This results with this is that the machine will run for 1 minute and then stop... is the car clean? Who knows. The machine doesn't care. The car was dirty. The machine ran for one minute, task complete.

while (car == dirty) {CleanCar()}

This results with the machine running for a minute, checking if the car is clean again and then running again until the car is clean (presumedly in the CleanCar function there is a piece of code that sets the car variable to clean if it is... if not the while statement would run forever)


Just wait till you see for loops.
For loops I understand perfectly. The problem I have is more in scripting engines. When I'm doing framework programming in C++, the difference between if/while is clear. But in engines that have a single update state, which is updated once per frame, then if does the same thing under a condition. For instance, say I want there to be an action when a player is standing on a trigger. If I use 'If' conditionals, the action will happen every frame, because the update function will evaluate that I am still on the trigger. The same happens with a wile function, like so:

// Psuedo code (this is updated once per frame)
if(collision with trigger) {
ResultingAction();
}

OR

while Collision
{ Resulting Action
}
What engine(s) specifically are you scripting against? Something sounds fishy here.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]


For loops I understand perfectly. The problem I have is more in scripting engines. When I'm doing framework programming in C++, the difference between if/while is clear. But in engines that have a single update state, which is updated once per frame, then if does the same thing under a condition. For instance, say I want there to be an action when a player is standing on a trigger. If I use 'If' conditionals, the action will happen every frame, because the update function will evaluate that I am still on the trigger. The same happens with a wile function, like so:

// Psuedo code (this is updated once per frame)
if(collision with trigger) {
ResultingAction();
}

OR

while Collision
{ Resulting Action
}


The question then is how are you not getting in infinite loops?

in the while collision if the collision doesn't result in a destruction of the sprite or one of the sprites being moved would always lock up your program because the loop would continue on forever because at the end of a loop where one of those two things don't happen you'd still be in a collision and thus go through the loop again

Let's move beyond the fact that if you use the while loop wrongly you'd crash your game... and let's answer the pro vs con question, assuming the situation lends itself in such a way that it the ending results are the same in that the resulting action and the loop won't repeat. infinitely

The pro vs Con is as simple as stepping through the program..


Let's take the if first...

if(collision with trigger) {
ResultingAction();
}

Each line of code is 1 process "more or less" so...

This is 1 process "if(collision with trigger) {"
This is 1 process "ResultingAction();"


So in this code you have 2 processes no matter what.

Now for the while...

This line is processed... "while Collision"
Here's your 2nd process "Resulting Action"


You're thinking..oh same number of lines, same number of processes... nope. It's not the line that is counted, but rather how many times it is gone over and changes based on some formatting... So with the while loop what happens is after that 2nd process the "while collision" is processed again.

This means that the If statement has 2 processes and the while statement has 3

Is this good? Is it bad? Well... it doesn't really matter but it's bad... Why?
You know that number for your processor? 3.02 GHz That is means you can run 3.02 trillion (i think it's trillion, or maybe billion i forget) processes per second. So 1 extra in billions per second it will be unoticable, unless you do it a lot and there's always the chance with an improperly used loop you get caught in an infinite loop... so it ranges from noone cares to "I'm so sorry i crashed your computer" where as if you just use the if statement you don't have to worry about it
while is a loop contition, if is a one timer condition!
Thanks Durakken, that really clears it up. I appreciate it. :)

The question then is how are you not getting in infinite loops?


The answer, of course, is easy: the loop is not infinite because after some number of iterations (possibly just 1) the condition stops being true.


The pro vs Con is as simple as stepping through the program..


Let's take the if first...

if(collision with trigger) {
ResultingAction();
}

Each line of code is 1 process "more or less" so...

This is 1 process "if(collision with trigger) {"
This is 1 process "ResultingAction();"


So in this code you have 2 processes no matter what.

Now for the while...

This line is processed... "while Collision"
Here's your 2nd process "Resulting Action"


You're thinking..oh same number of lines, same number of processes... nope. It's not the line that is counted, but rather how many times it is gone over and changes based on some formatting... So with the while loop what happens is after that 2nd process the "while collision" is processed again.

This means that the If statement has 2 processes and the while statement has 3[/quote]

Technically correct, although in practice it can be far more complex than that. The important semantic difference is that if statements only execute the associated code zero times or once, whereas loops execute any number of times from 0 to infinity, depending on how long the condition remains true. The overhead of checking the condition must occur after every iteration of the loop.


Is this good? Is it bad? Well... it doesn't really matter but it's bad... Why?
You know that number for your processor? 3.02 GHz That is means you can run 3.02 trillion (i think it's trillion, or maybe billion i forget) processes per second. So 1 extra in billions per second it will be unoticable, unless you do it a lot and there's always the chance with an improperly used loop you get caught in an infinite loop... so it ranges from noone cares to "I'm so sorry i crashed your computer" where as if you just use the if statement you don't have to worry about it
[/quote]

This is where you've ventured into outright incorrectness.

3 GHz, for instance, means three billion (not trillion), i.e. 3,000,000,000 cycles per second. Even the most simple machine instructions can last much longer than one cycle, and some can take literally thousands of cycles. Moreover, the translation from high-level code (especially game scripts) to machine instructions is far from trivial. You know all that time you sit around waiting for your compiler to do stuff? That's the process of translating your code into machine instructions. It isn't simple, and it isn't easy, and it sure as hell isn't a 1:1 mapping from code operations to machine instructions. In fact, a typical game engine scripting language may process several thousand machine instructions just to execute one line of script code - even simple lines. Throw in complexity like cache coherency issues, pipeline stalls, branch mispredictions, and so on, and suddenly that one tiny little "it shouldn't matter" line of code is chewing up millions of CPU cycles, i.e. milliseconds. Do something that lasts 10 milliseconds 100 times, and you have a 1 second delay. Your framerate just went from "hey this game is fun" to "wtf I've been cemented to the floor."

Optimizing code for performance is a very deep art. Yes, it pays not to be wasteful with things like "while(only_happens_once)" loops, but there's another tradeoff to consider here: premature optimization is evil. Wasting your time worrying about something that only happens for a microsecond every 30 seconds is totally unproductive. The important thing when it comes to optimizing code is to profile. Measure (never guess) where your code is genuinely slow, and speed that up; everything else is more or less inconsequential.

Wielder of the Sacred Wands
[Work - ArenaNet] [Epoch Language] [Scribblings]

This topic is closed to new replies.

Advertisement