From 4571644262997457333
X-Google-Thread: 7894ca11fe,d47b345505a72a70,start
X-Google-Attributes: gid7894ca11fe,public,usenet
X-Google-NewGroupId: yes
X-Google-Language: ENGLISH,ASCII-7-bit
Path: g2news2.google.com!news1.google.com!newsfeed.stanford.edu!news.kjsl.com!news.alt.net!frodo.cs.rpi.edu!not-for-mail
From: Jared Grubb <jared.grubb@gmail.com>
Newsgroups: comp.std.c++
Subject: for-else: adding else to for loops
Date: Fri,  7 Aug 2009 11:56:19 CST
Organization: http://groups.google.com
Lines: 58
Sender: cppmods@cs.rpi.edu
Approved: austern@google.com
Message-ID: <5d82cd6c-2a22-4dd7-8c7d-790b579533ea@d15g2000prc.googlegroups.com>
NNTP-Posting-Host: netlab.cs.rpi.edu
Content-Type: text/plain; charset=ISO-8859-1
To: (Usenet)
Return-Path: <cppmods@ruralroute.cs.rpi.edu>
X-Original-Date: Thu, 6 Aug 2009 16:04:01 -0700 (PDT)
X-Submission-Address: std-c++@netlab.cs.rpi.edu
Xref: g2news2.google.com comp.std.c++:1230

I am both a Python and C++ developer, and there is one feature in
Python that I've grown to appreciate, and that I wish C/C++ had. In
Python, loops can have an else clause; the else clause gets executed
when the loop condition fails (but not when the loop is exited via a
break, return, or exception). For a dummy example:

auto iter = my_list.begin();
for ( ; iter != lst.end(); ++iter)
{
     if (*iter == NEEDLE) break;
}
else
{
    cout << "needle not in the list";
}

For a second example:

for (unsigned try = 0; try < MAX_TRIES; ++try)
{
     bool success = did_it_work();
     if (success) break;
     sleep(POLL_PERIOD);
}
else
{
     // Never worked
}

Being able to insert some code that runs when the loop condition is
false can be useful, even if it is somewhat rare. I've seen examples
in live code where developers solve this by:
1) re-testing the loop condition,
2) using an extra flag-variable declared outside of the for loop that
can be tested after the for loop finished (e.g., put "bool
success=false" outside the loop in the second example),
3) by encapsulating the for-loop in a separate function (the "break"
becomes "return" and the extra code follows the for loop).

The first two solutions result in code that is not as readable and
even awkward (once you know how "for-else" works -- it's a little
strange at first glance). The third solution is probably the best way
to do it, but sometimes encapsulating the for-loop out is not easy or
nice.

I tried to find if this has ever been discussed, and I haven't been
able to find any previous discussion on this construct. So, I was
curious if anyone else had an opinion on whether this kind of
construct would be useful.

Jared

--
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@netlab.cs.rpi.edu]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://www.comeaucomputing.com/csc/faq.html                      ]



