How to workaround assignment not allowed in a condition?

Dennis dkorpel at gmail.com
Wed Oct 12 09:24:46 UTC 2022


On Wednesday, 12 October 2022 at 02:15:55 UTC, Steven 
Schveighoffer wrote:
> Porting some C code to D
>
> This results in an error:

I had the same issue, where the pattern was this:

```C
void f()
{
     int err;
     if (err = some_api_call()) {
         printCode(err);
         return;
     }
     if (err = some_other_api_call()) {
         printCode(err);
         return;
     }
}
```
I would either declare the variable in the if statement:

```D
void f()
{
     if (auto err = some_api_call()) {
         printCode(err);
         return;
     }
     if (auto err = some_other_api_call()) {
         printCode(err);
         return;
     }
}
```

Or take the assignment out of the condition:

```D
void f()
{
     int err;
     err = some_api_call();
     if (err) {
         printCode(err);
         return;
     }
     err = some_other_api_call();
     if (err) {
         printCode(err);
         return;
     }
}
```

I haven't seen it used in a while condition yet, perhaps you can 
transform that into a for loop?


More information about the Digitalmars-d-learn mailing list