How to workaround assignment not allowed in a condition?

Steven Schveighoffer schveiguy at gmail.com
Wed Oct 12 13:35:10 UTC 2022


On 10/12/22 7:46 AM, Dennis wrote:
> On Wednesday, 12 October 2022 at 10:09:31 UTC, Steven Schveighoffer wrote:
>> 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?
> 
> I looked into it, there are actually two different places where dmd 
> files the very same error:
> 
> ```D
> void main()
> {
>      int x;
> 
>      // Directly in loop conditions
>      if (x = 3) {}
>      while (x = 3) {}
>      for (; x = 3; ) {}
> 
>      // when an assignment is implicitly cast to a boolean
>      bool b = !(x = 3);
>      assert(x = 3);
>      true && (x = 3);
> }
> ```
> 
> Wrapping in `==` actually does do the trick, but you need to get rid of 
> the `!` operator. So instead of `while(!(x=3) == true)` make it `while 
> ((x=3) == false)`

Wow thanks!

However, this is tricky, because what is happening is instead of the (x 
= 3) being converted to bool (which would have the same error), `true` 
is being converted to `int`. So if you had a condition like `while(x = 
3)`, you would have to do `while((x = 3) != false)` and not `while((x = 
3) == true)`

Or, you can just say `while((x = 3) != 0)`

But yes, this is the solution.

-Steve


More information about the Digitalmars-d-learn mailing list