Proposal of a general do-while loop
Charles D Hixson
charleshixsn at earthlink.net
Sat Jul 21 07:34:22 PDT 2007
Taro Kawagishi wrote:
> Hello all,
>
> every once in a while I feel uneasy when I find I can't fit my logic into a do-while or while loop in a concise way.
> Here is a C++ example:
>
> void
> find_string_occurrences(const string& text, const string& pattern) {
>
> // listing 1
> size_t pos = text.find(pattern, 0);
> while (pos != string::npos) {
> cout << "pattern found at " << pos << "\n";
> ++pos;
> pos = text.find(pattern, pos);
> }
>
> }
> ...
to me the best solution would appear something along the lines of:
loop
{ size_t pos = text.find(pattern, 0);
// declare a new pos on each iteration??
if (pos == string::npos) break;
cout << "pattern found at " << pos << "\n";
// tango is not standard D, but I think I understand
// what you are doing
++pos;
pos = text.find(pattern, pos);
}
I'd prefer the Ada-esque
exit when (pos == string::npos);
but that means introducing new key words (more than just
"loop"). OTOH, I guess there's nothing wrong with having an
un-parameterized "do" instead of loop, as in:
do
{ ... do stuff ...
when(condition) break;
}
in the case the "when" is semantically the same as an if, but
it clarifies what's going on. One could limit it's use to
"only usable within a do loop". But I would prefer the syntax
of either:
exit when (condition);
or
break when (condition);
as I feel that these are clearer.
More information about the Digitalmars-d
mailing list