Concerns about N3587 "For Loop Exit Strategies"

80 views
Skip to first unread message

Mikhail Semenov

unread,
Apr 20, 2013, 6:31:51 AM4/20/13
to std-pr...@isocpp.org

The proposal N3587 does not provide better syntax. It looks at the following "ugly" code:

something_t last; // Extra construction here.
for (auto& i : c)
{
    if (some_condition(i))
    {
        last = i; // Extra copy here
        goto EARLY;
    }
    do_something(i);
}
do_stuff();
goto DONE;
EARLY:
do_something_else(last);
DONE:

and states that new syntax is needed. But the above loop can be easily re-written using better forms:
(1)
bool ok = true;
for (auto& i : c)
{
    if (some_condition(i))
    {
        ok = false;
        do_something_else(i);
        break;
    }
    do_something(i);
}
if (ok)
{
    do_stuff();
}

(2)
for (auto& i : c)
{
    if (some_condition(i))
    {       
        do_something_else(i);
        go EARLY;
    }
    do_something(i);
}
do_stuff();
EARLY:;

The proposal goes ahead and offers new syntax:
if for (auto& i : c)
{
    if (some_condition(i)) break;
    do_something(i);
}
{
    do_stuff(); // normal termination
}
else
{
    do_something_else(i); // early exit
}

It does not look better than the above written two pieces of code.
Besides it may be confusing if the loop code uses more space:
the code for normal termination can be easily misinterpreted.


 

Reply all
Reply to author
Forward
0 new messages