In article <santa-DE15CC.17545025022008@[EMAIL PROTECTED]
>,
Santa Claus <santa@[EMAIL PROTECTED]
> wrote:
> i have a simple question. what's the difference between these two ways
> of handling while?
>
> 1)
> while (condition)
> {
> do something
> change condition if needed
> }
>
> 2)
> do
> {
> do something
> change condition if needed
> }
> while (condition)
If the condition is zero/false, the first will never be executed while
the second will run at least once. More broadly, since the "condition"
may be function call instead of just a value, there may be side effects.
> personally, i prefer version 1 but that means that condition would have
> to be preset before entering into the loop and there's a possibility of
> it not going into the loop based on the condition when it enters the
> loop.
I prefer the version that accomplishes the task I'm trying to get done
at that point in the code with minimal obfuscation.
> another thing i'd like to know is why do a while false or while true?
> shouldn't you actually TEST for something instead of testing a constant
> and then breaking out if an inside test results in something?
Partly it's a matter of style, but it's *also* serves as a form of
do***entation regarding the intent. Starting a loop with "while(1)" is a
good indication that you really want this block to run "forever" until
and unless some exceptional situation (and there may be more than one of
these) arises. That while practically you do expect the loop to
eventually exit, you expect it to be a condition that's complex and/or
rare.
> this is what i've seen once (from a teacher no less). shouldn't it be
> "while condition" instead of "while true"?
>
> while (true)
> {
> do something
> if (some condition)
> {
> break;
> }
> }
Because if the condition started as false - something that again may not
be as trivial to rig as an assignment to a variable - the 'do something'
part would never execute.
> ok ok, enough of me ranting on and on. i'll get off my soapbox but i
> WOULD like to know just for curiosity's sake.
Curiosity's fine, and certainly better than blind assumption like the
person I saw once asserting that
i = 0;
while(i < 10)
{
//...
i++;
}
was "literally" several times faster than
for(i=0; i < 10; ++i)
{
//...
}
When challenged he allowed that when he said "literally several times"
he meant "slightly" and after too much further discussion finally
understood that the difference he had seen was a quirk of the way his
compiler optimized that particular stretch of code rather than a
reliable behavior of C.
That said, there would have been better places to ask this question
since it has not a thing to do with Objective-C. I'm thinking
comp.programming.


|