Sign in to follow this  
MERKB7661

If vs. While

Recommended Posts

MERKB7661    120
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).

Share this post


Link to post
Share on other sites
Nypyren    12065
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:

[code]
start:

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

goto start;
}

end:
[/code]

Share this post


Link to post
Share on other sites
SimonForsman    7642
[quote name='MERKB' timestamp='1309026751' post='4827647']
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).
[/quote]

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.

Share this post


Link to post
Share on other sites
Durakken    692
[quote name='MERKB' timestamp='1309026751' post='4827647']
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).
[/quote]

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.

Share this post


Link to post
Share on other sites
MERKB7661    120
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
}

Share this post


Link to post
Share on other sites
Durakken    692
[quote name='MERKB' timestamp='1309032623' post='4827671']
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
}
[/quote]

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

Share this post


Link to post
Share on other sites
DarrenHorton    110
What I do now is to generally remember language keywords.
---------------------------------------------------
This works inside Visual Studio...

When I need to know more about the keyword I type the word and double click it to highlight.

I can then hit F1 and be taken to the exact keyword help page.

In your example this would give examples of the while and if loops in your language.

So very quickly you can find the information you need.

Share this post


Link to post
Share on other sites
landlocked    103
Using a while loop for code that is supposed to only run once is just bad programming. Use an if statement if you're only meaning to do something once. Use a while loop if you're wanting to iterate over some collection or series of routines that change based on the previous loops execution results until you reach your desired result. That's about it.

Share this post


Link to post
Share on other sites
Durakken    692
[quote name='ApochPiQ' timestamp='1309046239' post='4827730']
[quote name='Durakken' timestamp='1309034476' post='4827682']
The question then is how are you not getting in infinite loops?[/quote]

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.


[quote]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 [i]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. [/i]The overhead of checking the condition must occur after every iteration of the loop.


[quote]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 [i]cycles[/i] 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 [i]profile. [/i]Measure (never guess) where your code is [i]genuinely[/i] slow, and speed that up; everything else is more or less inconsequential.
[/quote]

Ok, look, I don't want to hi-jack this thread, and I have to point out that since I answered the question MERKB was having CORRECTLY the thread no longer has a point so it really isn't a problem, I have to deal with you and your rudeness.

First quoted area. It's obvious that I know why it isn't happening. The question isn't a matter of how does an infinite loop happen. It is how has he not stumbled into them constantly if he was using whiles in place of ifs. It would happen all the time if he was doing that. You need to read what is be said/asked in the context of how it's given before answering.

Second quoted area. Again. This is obvious that I know this and is what is explained, with different language, but we said the exact same thing. The difference mine is actually easier to grasp as to what the problem is for most people. He's probably read something similar to what you said hundreds, if not thousands of times, and it didn't click, obviously, since he's asking the question.

Third quoted area. Dive into total incorrectness? See this is the only part that I said which is "wrong" partially and I appreciate that you corrected me where I was wrong, but "total incorrectness"? The two things you "corrected me on were?
I said 3.02 GHz = 3.02 Trillion OR Billion processes
You said 3.02 GHz = 3.02 Billion processes
Am I totally wrong there? hrmm nope... That's why i said it was this or that.

I said each line of programming is 1 process
you said each line of programming can be thousands of processes

Am I totally wrong here? No. The fact is I could have kept it to 1 line = 1 process to simplify and get the point across because nebulously saying it thousands of processes really doesn't mean much because our brain can't process the idea of huge numbers well and the less concrete the harder it becomes, but I will be honest that I did think that 1 line = 1 process, but had I thought it out I probably wouldn't have, but I'd still think in terms of 1 line = 1 process for the shear benefit of having a number there that would give me an indication on how efficient the code is running vs how efficient it could be.


So you're rude and incorrect. Plus I bet you're the person who gave the -1 reputation on that post. If you're not still, by calling someone incorrect that ISN'T you confuse people and I think that is an incredibly d-bag thing to do, especially as a moderator.
If your the one who the -1 that post, or to the person who did, I have to point out I'm the person that answered the question and I did so correctly. If you think that deserves negative reputation you are an <expletive> I'm sure you can make up your own name calling. Seriously, I help and you give neg rep? What the hell is wrong with you?

Share this post


Link to post
Share on other sites
JackTheRapper    150
[quote name='Durakken' timestamp='1309066948' post='4827793']
Third quoted area. Dive into total incorrectness? See this is the only part that I said which is "wrong" partially and I appreciate that you corrected me where I was wrong, but "total incorrectness"? The two things you "corrected me on were?
I said 3.02 GHz = 3.02 Trillion OR Billion processes
You said 3.02 GHz = 3.02 Billion processes
Am I totally wrong there? hrmm nope... That's why i said it was this or that.[/quote]
Cycles. 3.02 billion [i]cycles[/i]. This does not mean that in a given second 3.02 billion <insert operation here> can be performed.

[quote]
I said each line of programming is 1 process
you said each line of programming can be thousands of processes

Am I totally wrong here? No. The fact is I could have kept it to 1 line = 1 process to simplify and get the point across because nebulously saying it thousands of processes really doesn't mean much because our brain can't process the idea of huge numbers well and the less concrete the harder it becomes, but I will be honest that I did think that 1 line = 1 process, but had I thought it out I probably wouldn't have, but I'd still think in terms of 1 line = 1 process for the shear benefit of having a number there that would give me an indication on how efficient the code is running vs how efficient it could be.[/quote]
Again, your simplification is incorrect and thus misleading. Even for a trivial arithmetic operation it could take many hundreds of clock cycles just to retrieve the necessary data from system memory.


[quote]So you're rude and incorrect. Plus I bet you're the person who gave the -1 reputation on that post. If you're not still, by calling someone incorrect that ISN'T you confuse people and I think that is an incredibly d-bag thing to do, especially as a moderator.
If your the one who the -1 that post, or to the person who did, I have to point out I'm the person that answered the question and I did so correctly. If you think that deserves negative reputation you are an <expletive> I'm sure you can make up your own name calling. Seriously, I help and you give neg rep? What the hell is wrong with you?
[/quote]
Actually, I thought he was fairly civil and I didn't read any malicious intent into his response. Fact of the matter is, incorrect information (especially in the beginner's forum) only serves to add confusion and misinformation. As a moderator, he has even more on an onus to rectify misleading or outright incorrect information in such a forum. There's no point in getting prickly and defensive about it, just take it in good faith and move on. Rating a post down isn't a personal slight against the poster, it's simply a means of saying "the information in this post was not helpful", that's all. Someone may come along and point out errors in my post and then rate me down, it's no big deal.

Share this post


Link to post
Share on other sites
Durakken    692
[quote name='JackTheRapper' timestamp='1309088156' post='4827850']
[quote name='Durakken' timestamp='1309066948' post='4827793']
Third quoted area. Dive into total incorrectness? See this is the only part that I said which is "wrong" partially and I appreciate that you corrected me where I was wrong, but "total incorrectness"? The two things you "corrected me on were?
I said 3.02 GHz = 3.02 Trillion OR Billion processes
You said 3.02 GHz = 3.02 Billion processes
Am I totally wrong there? hrmm nope... That's why i said it was this or that.[/quote]
Cycles. 3.02 billion [i]cycles[/i]. This does not mean that in a given second 3.02 billion <insert operation here> can be performed.

[quote]
I said each line of programming is 1 process
you said each line of programming can be thousands of processes

Am I totally wrong here? No. The fact is I could have kept it to 1 line = 1 process to simplify and get the point across because nebulously saying it thousands of processes really doesn't mean much because our brain can't process the idea of huge numbers well and the less concrete the harder it becomes, but I will be honest that I did think that 1 line = 1 process, but had I thought it out I probably wouldn't have, but I'd still think in terms of 1 line = 1 process for the shear benefit of having a number there that would give me an indication on how efficient the code is running vs how efficient it could be.[/quote]
Again, your simplification is incorrect and thus misleading. Even for a trivial arithmetic operation it could take many hundreds of clock cycles just to retrieve the necessary data from system memory.


[quote]So you're rude and incorrect. Plus I bet you're the person who gave the -1 reputation on that post. If you're not still, by calling someone incorrect that ISN'T you confuse people and I think that is an incredibly d-bag thing to do, especially as a moderator.
If your the one who the -1 that post, or to the person who did, I have to point out I'm the person that answered the question and I did so correctly. If you think that deserves negative reputation you are an <expletive> I'm sure you can make up your own name calling. Seriously, I help and you give neg rep? What the hell is wrong with you?
[/quote]
Actually, I thought he was fairly civil and I didn't read any malicious intent into his response. Fact of the matter is, incorrect information (especially in the beginner's forum) only serves to add confusion and misinformation. As a moderator, he has even more on an onus to rectify misleading or outright incorrect information in such a forum. There's no point in getting prickly and defensive about it, just take it in good faith and move on. Rating a post down isn't a personal slight against the poster, it's simply a means of saying "the information in this post was not helpful", that's all. Someone may come along and point out errors in my post and then rate me down, it's no big deal.
[/quote]



I have no problem with being corrected WHERE I am wrong. That is not what he did. He said something was totally wrong which wasn't, and implied the rest was wrong as well which wasn't. And again, the simplification is better for thinking and practical purposes as explained.

Marking someone's rep down when they help is wrong. It makes the whole point of that system worthless and it gives people the wrong impression.
Did I answer the question? yes
Did I have intention of doing so thus being helpful? yes
Was I snide, snarky, downing of any one else? no
Then what was the reason for being repped down? As far as I can figure is that someone didn't like the fact that i used more concrete and useful way of thinking about being efficient and I said something is this or that and it was this or that.

And again how is it not helpful? Had I not posted that post THE QUESTION WOULD NOT HAVE BEEN ANSWERED.
And even if I was completely wrong no one else answered the question.. not even, and most importantly, the one who said I was wrong.
Seriously, even if you had said "I'm down repping you cuz have wrong info here" at least make that info be the info that actually matters to the subject at hand.
That's actually a freakin logical fallacy v.v

Share this post


Link to post
Share on other sites
owl    376
It never had occurred to me that one could make such an argument from the IF and WHILE statements.

OP: Your question, that at first looks silly for the experienced programmer made me remember that time when I wasn't experienced myself thus the big battle was to stop completing the voids with imagination and start filling them with actual knowledge. From my experience, that journey is totally worth it. Keep up the good battle. :)

Share this post


Link to post
Share on other sites
Durakken    692
[quote name='ApochPiQ' timestamp='1309119071' post='4827982']
stuff
[/quote]

No you no one answered what the pros and cons were and no one was going to because looking at other posts through out the forum the next stage of inquiry was going to be "let's see some code" because you weren't actually understanding what was being asked and believed that the person was having problem with a specific code and asked the question in a funny way. And you obviously can't read context because well i pointed that out that the first thing i asked that you responded to you didn't get it.


see here's the problem, You just admitted that I AM RIGHT, and then you try to say I'm totally wrong. Totally wrong means that I am wrong about every point about in the entire thing i said. Am I? NO. And the way you said it implies, like I said before, that the rest of what I said was wrong.

The point that you are saying is not the question or answer of the post and it is insignificant information really. I mean what you did is akin to someone asking someone what color the sky is and them answering that sky has no color and that it is simply a process of reflection and how our eyes take in various wavelengths of light that make it the color blue, red, or orange, and then you smacking them upside the head because thy used the word reflection instead of refraction. Is it wrong to say reflection rather than refraction? yes, but is the person totally wrong? Hell no, and that person should be encouraged for going out of their way to give an answer that is far more informative and accurate than just saying blue. The refraction part is insignificant information to the question being asked, but the answer is still correct.

So what then should you do in this situation? Do you tell them they are totally wrong? NO
You tell them that it's refraction and not reflection and explain the difference. And you could even try to explain how the terms got confused to the person, dependent upon the situation. And because of the added information that could lead to greater understanding you tell them that they are doing a good job.

If I'm to take what you said then I am forced to believe that my analogy is correct and you are saying that I am "totally" wrong because I said reflection instead of refraction instead of saying, great answer but here's where you messed up, you are saying crap answer you fail. That is counter productive to what this site is trying to do and is flawed way of doing things, which is why we don't do things that way.

[quoted]
[color=#1C2837][size=2]GDNet, in case you hadn't ever noticed, is ranked [i]extremely[/i] well in search engines like Google. This means that people will probably be stumbling across this thread in several years' time, long after neither of us is paying attention or available to dispel misconceptions. It is a core responsibility of posting on a long-lived internet forum to ensure that your information is factually accurate. You have something of a duty here to ensure that you're being helpful, lest you (god forbid) get down-rated for peddling inaccuracies. The rating system exists to act as a control mechanism precisely so that people think twice before they post. It's not a personal remark about your manhood, for goodness sake, it's an indicator [i]that your post was not helpful.[/i][/size][/color]
[/quoted]

As i pointed out. I have no problem being corrected where I am wrong.
But you do point out what the problem is. My post IS helpful and answers the question that the poster was asking ACCURATELY.
So what you did you used a system that was meant to lead people away from wrong information away from RIGHT information.
Do you see the problem?
And it's made worse now by the fact that you are now stating that you agree with the important pertinent part of what was posted.

But hey, some of us get down repped when we post helpful accurate information and others get up repped when we're d-bags because we're moderators.
And as far as others answering is question, sorry, no, they didn't. We established that he already knew what a a while statement an if statement did. repeating to someone what they already know does not answer a question. The question was about the pros and cons of such things and which is better to use and why. For someone that "read" what was posted you sure can't read.

Share this post


Link to post
Share on other sites
MaulingMonkey    1728
[quote]And it's made worse now by the fact that you are now stating that you agree with the important pertinent part of what was posted.[/quote]
One's entire post should be important and pertinent. There were parts that were correct and parts that were incorrect. This is a tremendously far cry from "totally correct". In mathematics, this wouldn't even be dignified with "partially correct": It'd just be wrong.

And this is how you're being rated. Confirming oversimplifications, inaccuracies, and outright errors could've gotten those confirmations rated up, possibly ending up with a total increase.

Instead we have a tangential, inflammatory, combative, and name calling line of drivel in response to slights that only you perceived, that I doubt convinces any to believe you when you say "I don't want to hi-jack this thread". There are better venues if you truly meant that: Including bringing up ApochiPiQ's supposedly insulting behavior up with him or another moderator directly.

And this is how you're continuing to be rated.

Share this post


Link to post
Share on other sites
Durakken    692
[quote name='MaulingMonkey' timestamp='1309137312' post='4828062']
[quote]And it's made worse now by the fact that you are now stating that you agree with the important pertinent part of what was posted.[/quote]
One's entire post should be important and pertinent. There were parts that were correct and parts that were incorrect. This is a tremendously far cry from "totally correct". In mathematics, this wouldn't even be dignified with "partially correct": It'd just be wrong.
[/quote]

This isn't math.
It's English.

And it isn't about being 100% correct in the first place. It is about getting someone answer and making them understand it. Sometimes that requires dumbing down and simplifying the concept.

Share this post


Link to post
Share on other sites
owl    376
[quote name='Durakken' timestamp='1309137804' post='4828065']
This isn't math.
It's English.

And it isn't about being 100% correct in the first place. It is about getting someone answer and making them understand it. Sometimes that requires dumbing down and simplifying the concept.
[/quote]

And sometimes it is about not making an scene and leave the stage with some dignity.

In my case sometimes it's about ridiculing myself and blame the booze, but well, from funny to sad and back there is just a step.

Share this post


Link to post
Share on other sites
ApochPiQ    23010
MERKB, genuinely sorry about the way your thread turned out. Hopefully at least it was educational [img]http://public.gamedev.net/public/style_emoticons/default/smile.gif[/img]


I'm petitioning the mod team to close this down before it gets truly ugly. I'd do it myself, but that's an obvious conflict of interest at this point, and against policy anyways, so... preemptive apologies for any more off-topic stuff that leaks in before someone comes by to lock it.

Share this post


Link to post
Share on other sites
Guest
This topic is now closed to further replies.
Sign in to follow this