Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Intricate loop

12 views
Skip to first unread message

Alf P. Steinbach

unread,
Jul 25, 2022, 8:49:02 AM7/25/22
to
This code parses an unsigned decimal integer spec with possible group
delimiters.

Since it's intricate it can probably be very much simplified?

Result_uint result = 0;
bool overflowed = false;
char ch; // Declared here to be accessible to the
loop's update expression.
Prev_char previous_ch = '\0';
for( p_end = p_first; p_end != p_beyond; previous_ch = ch, ++p_end ) {
ch = *p_end;
WITH_CONST( ch ) {
if constexpr( group_delimiters_allowed ) {
if( ch == group_delimiter ) {
if( previous_ch == group_delimiter ) {
return Ret( no_result,
Error::consecutive_group_delimiters );
}
continue;
}
}
if( not( ch %in% ascii::digits ) ) { return result; }
const Result_uint before = result;
result = 10*result + (ch - '0');
if( result < before ) { overflowed = true; }
}
}

... where `WITH_CONST` just adds `const`-ness to the specified name so
that it's provably not modified in that code block, and where the
`Prev_char` type by default is `char`, but can be dummy (optimized away
operations) when code is instantiated to parse without group delimiters.

I declared `ch` before the loop so it can be accessed by the `for` loop
head's update expression, so that that expression can handle the
`continue` statement.

I guess if one can get rid of the `continue` then one can move the
declaration of `ch` inside the loop and just say directly that it's `const`?

- Alf

Paavo Helde

unread,
Jul 25, 2022, 9:25:33 AM7/25/22
to
I see your obscure WITH_CONST macro and counter with my obscure
UPDATE_AND_CONTINUE macro:

#define UPDATE_AND_CONTINUE(a,b) {a = b; continue;}

std::string_view input {p_first, p_beyond-p_first};
Prev_char previous_ch = '\0';

for(const char ch: input) {
if (/*...*/) {
if (/*....*/) {
// ...
UPDATE_AND_CONTINUE(previous_ch, ch);
}
}
// ...
UPDATE_AND_CONTINUE(previous_ch, ch);
}


Who says my macro is uglier than yours?




Alf P. Steinbach

unread,
Jul 25, 2022, 10:01:33 AM7/25/22
to
Heh :-), it's certainly less reusable functionality, but it's an idea.

And I like fresh ideas.

Just a shame that C++ doesn't yet formally support push and pop of
macros so that one can freely use local macros...
<url:
https://docs.microsoft.com/en-us/cpp/preprocessor/push-macro?view=msvc-170>
<url: https://gcc.gnu.org/onlinedocs/gcc/Push_002fPop-Macro-Pragmas.html>

I would also have liked language support for `WITH_CONST`. There's the
whole $ space available for new keywords. It could be `$with_const`.

Re the `string_view`:

that might seem smart but part of the parsing effect is to produce a
final `p_end`, beyond the number spec, where the caller can continue
higher level parsing (if any). That's also the reason for the boolean
`overflow`. To move the `p_end` beyond the spec even if overflow.

Thanks,

- Alf
0 new messages