How to workaround assignment not allowed in a condition?

Steven Schveighoffer schveiguy at gmail.com
Wed Oct 12 10:09:31 UTC 2022


On 10/12/22 5:24 AM, Dennis wrote:
> 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;
>      }
> }
> ```

The code in question doesn't follow this pattern. The target in question 
is inside a struct that is passed in via pointer

The original code looks like this:

```c
static int
sinfl_build_tbl(struct sinfl_gen *gen, unsigned *tbl, int tbl_bits,
                 const int *cnt) {
   int tbl_end = 0;
   while (!(gen->cnt = cnt[gen->len])) {
     ++gen->len;
   }
```

So using `auto` isn't going to work here, I need to get the value out to 
the final destination. And I can't do that inside the loop because the 
condition may already have terminated it.

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

That also was suggested on discord, the issue with it is that then I 
have to repeat the assignment code for the iteration.

As you are probably more aware than others, while porting code, you 
don't want to refactor at the same time. Simple syntax changes are ok, 
as long as the meaning stays the same. Using a for loop is a possible 
change that's equivalent, but I'd rather avoid it if possible.

I was expecting there to be a way to write problematic code where the 
compiler says "OK, if you wrote it that way, you really mean it, I'll 
shut up". But there doesn't appear to be any way to do that in this case.

I'm actually very surprised that just wrapping the statement in an == 
expression doesn't do the trick, what is the possible logic behind 
outlawing that?

-Steve


More information about the Digitalmars-d-learn mailing list