ZeroPhase
ZeroPhase

Reputation: 647

Can declarations and conditions be separated in while loops?

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?

Upvotes: 0

Views: 98

Answers (3)

Lorah Attkins
Lorah Attkins

Reputation: 5856

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.

Upvotes: 0

Jarod42
Jarod42

Reputation: 217398

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
{
// ...
}

Upvotes: 2

ZeroPhase
ZeroPhase

Reputation: 647

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.

Upvotes: -1

Related Questions