[Issue 10638] Assignment can't be used as a condition

via Digitalmars-d-bugs digitalmars-d-bugs at puremagic.com
Fri Nov 11 12:32:39 PST 2016


https://issues.dlang.org/show_bug.cgi?id=10638

Kevin <kevin at brogan.ca> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
             Status|NEW                         |RESOLVED
                 CC|                            |kevin at brogan.ca
         Resolution|---                         |WONTFIX

--- Comment #3 from Kevin <kevin at brogan.ca> ---
D has a number of language features (restrictions?) that are designed to make
buggy code less likely to happen.

A missing equals sign in a comparison is one of those common bugs.

To get around it, you need to be explicit with your intent. An "if statement"
is a poor example to use because you can always place the assignment before the
comparison, but take for example a while loop:

while(line = file.readln())
{
  ...
}

Since readln will return a null string when you reach the end of file input,
the loop will terminate. However, you can't assign in a comparison, so what to
do?

One option is to be explicit in your intent by using a compound statement.

while(line = names.readln(), line)
{
  ...
}

A better option is to be explicit in your comparison as well, using this
example from the documentation:

while ((line = stdin.readln()) !is null)
{
  ...
}


The example that you give isn't the best, since your assignment always
evaluates to true, but perhaps you would prefer these examples:

if (i = getValue(), i) { ... }
if ((i = getValue()) == 1) { ... }

--


More information about the Digitalmars-d-bugs mailing list