Skip navigation

Well, in Python, you can attach an ELSE to a WHILE statement like so:

# python
while oi.hasNext() :
  print oi.value
else :
  print 'oi had no values'

You can’t do that in C++, but you can do this instead:

// C
if( ! oi.hasNext() )
  print 'oi has no values' ;
else do
  print oi.value ;
} while( oi.hasNext() ) ;

I used else do instead of

if( ! oi.hasNext() )
  print 'oi has no values' ;
else while( oi.hasNext() )
  print oi.value ;

In case that oi.hasNext() has a side effect (such as advancing an iterator).. in this case, oi.hasNext() gets called twice before we ever try to read oi.value.



  1. Your python snippet will run the else clause every time, once the list is exhausted. The C-ish examples don’t have the same behavior. The else clause of a python while loop is executed unless the loop terminated due to a break statement.

    • Tom
    • Posted January 26, 2011 at 11:00 pm
    • Permalink

    One more thing that Dan didn’t state is that the else won’t get called on an exception or break in python.

  2. Nice way to get “while / else” behaviour in languages that don’t support it.

    Dan/Tom: Cheers. I didn’t realise that Python’s else executed every time (I thought it executed only if the loop failed the first time, and I guess Bobobobo thought that too). But honestly I think this behaviour is more useful than Python’s behaviour.

    • Slobodan
    • Posted December 1, 2015 at 8:01 pm
    • Permalink

    Thanks, this info is useful.
    I’m not C++ guru, but not to be able to write while else loop is just plain stupid.
    And this is yr 2015.
    Worst thing is developers claim they dont have use for it:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: