0

I'm trying to write something like this in C++20 mode.

I see that C++17 can do this for if conditionals.

char *o = ch;
char *a = ch;
while (o = strstr(o, "||"), a = strstr(a, "&&");
            o != nullptr && a != nullptr)
{
}

Is there any comparable syntax for while loops doing assignment?

ZeroPhase
  • 649
  • 4
  • 21

3 Answers3

2

You might use for loop

for (auto* o = strstr(ch, "||"), a = strstr(ch, "&&"); // init-statement
     o && a; // Condition
     /*o = strstr(o, "||"), a = strstr(a, "&&")*/) // iteration_expression
{
// ...
}

Jarod42
  • 203,559
  • 14
  • 181
  • 302
  • It's just frustrating that it's not consistent in C++ currently. I'm sure in C++ 27 we'll have while loops with my syntax. Thanks. – ZeroPhase May 12 '21 at 08:19
0

C++ already supports compact assign and compare expressions, since assigning returns the updated value. What you describe can be written as:

char const *o = ch;
char const *a = ch;
    
while ((o = strstr(o, "||")) != nullptr && 
       (a = strstr(a, "&&")) != nullptr) { 
  /*...*/ 
}

or more succintly (since comparing with nullptr is just checking a truthy value):

char const *o = ch;
char const *a = ch;
    
while ((o = strstr(o, "||")) && (a = strstr(a, "&&"))) { 
  /*...*/ 
}

the only caveat is that due to short-circuiting, the second assignment only happens when the first condition evaluates to true. Here's an example.

Lorah Attkins
  • 5,331
  • 3
  • 29
  • 63
-1

Ended up going with.

char *o = strstr(ch, "||");
char *a = strstr(ch, "&&");
while (o != nullptr || a != nullptr)
{
    o += 2;
    if (o) o = strstr(o, "||");
    if (a) a = strstr(a, "&&");
}

That other syntax would have been more succinct for this. Wish C++ would allow that syntax for all loops and conditionals.

ZeroPhase
  • 649
  • 4
  • 21
  • 1
    What's the deal with `o += 2;`? If `o` is null to begin with, then what? And if by incrementing it it points to garbage, then what? – acraig5075 May 12 '21 at 05:57
  • Have to increment `o += 2` past `||` in the string or it keeps looping forever. I can put in the condition when needed. – ZeroPhase May 12 '21 at 07:10