digitalmars.D.learn - if (int bar = .. bug or some thing
- Joel (10/10) Oct 30 2017 The following code assert fails (bar == 1, not -10!). I've wasted
- Jonathan M Davis (15/25) Oct 30 2017 Why would you expect it to be -10? bar is assigned the result of foo() !...
- Joel (1/1) Oct 30 2017 Ok, thanks guys.
- codephantom (16/17) Oct 30 2017 why not throw in some UFCS too...just because you can ;-)
- Adam D. Ruppe (10/11) Oct 30 2017 Not a bug, but I do think it is an iffy design.
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;
}
Oct 30 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
Oct 30 2017
On Tuesday, 31 October 2017 at 04:27:27 UTC, Joel wrote:Ok, thanks guys.why not throw in some UFCS too...just because you can ;-) import std.stdio; void main() { int foo; if (foo.bar != 0) // would be nice if I could do: (int foo.bar != 0) { throw new Exception("foo.bar != 0"); } } auto bar(int x,) { return -10; }
Oct 30 2017
On Tuesday, 31 October 2017 at 04:08:12 UTC, Joel wrote:
if (int bar = foo() != 0) {
Not a bug, but I do think it is an iffy design.
That is more like:
int bar;
if(bar = (foo() != 0))
so the foo != 0 is evaluated first, which ends up being boolean
true or false, then THAT true/false value is converted to int and
assigned to bar, hence it becomes 0 or 1.
You can't really combine declaration and non-trivial comparison
in a single statement.
Oct 30 2017









codephantom <me noyb.com> 