Re: please explain this simple construct
On 31.10.2006 14:29, Jeffrey Schwab wrote:
jpbisguier@yahoo.ca wrote:
my instructor likes to use this construct in class but never really
explained why/how it works:
while (true)
{
if (something) return; // break from while
}
can someone shed some light how this works?
That is hideous. The loop will execute the block over and over again,
until "something" happens to be true at the same time the if statement
is executed. At that point, the whole function call will suddenly end.
That's different from an traditional "break," which just exits the
current loop. The (IMHO) preferable way to loop looks more like this:
while(!something) {
//...
}
I don't find a "return" hideous - certainly not more than a "break". In
fact, I usually prefer "return" inside a loop over a "break". The
"return" gives pretty easy short circuit exit and IMHO it is far
superior in cases like this:
public Foo findIt( String name ) {
for ( Iterator iter = myFoos.itererator(); iter.hashNext(); ) {
Foo f = (Foo) iter.next();
if ( name.equals( f.getName() ) ) {
return f;
}
}
// alternatively throw an exception
return null;
}
Using the loop condition to break the loop makes this piece of code much
more complex and probably also less efficient.
Kind regards
robert