if (int bar = .. bug or some thing
Jonathan M Davis
newsgroup.d at jmdavisprog.com
Tue Oct 31 04:17:08 UTC 2017
On Tuesday, October 31, 2017 04:08:12 Joel via Digitalmars-d-learn wrote:
> The following code assert fails (bar == 1, not -10!). I've wasted
> a bit of time because of this happening.
>
> void main() {
> if (int bar = foo() != 0) {
> assert(bar == -10);
> }
> }
>
> auto foo() {
> return -10;
> }
Why would you expect it to be -10? bar is assigned the result of foo() != 0,
which is a boolean result and will be either true or false. When that's
assigned to int, a conversion occurs, and that conversion treats true as 1
and false as 0. If you want the result to be -10, then you need to assign
the result of foo() to bar, not the result of foo() != 0. Now, because 0 is
treated as false, you could probably still do
if(int bar = foo())
rather than something like
int bar = foo();
if(bar != 0)
but regardless, the result of foo() != 0 is going to be bool, not int, so
all you'll ever get out of it is true or false, which will then be 1 or 0 if
converted to int.
- Jonathan M Davis
More information about the Digitalmars-d-learn
mailing list