Thread overview | ||||||
---|---|---|---|---|---|---|
|
February 10, 2009 error in return statement | ||||
---|---|---|---|---|
| ||||
possibly error in return statement: ==== bool fn1(Object o1, Object o2 ) { return o1.opEquals(o2); // opEquals return int } ==== compiler writes: "Error: cannot implicitly convert expression (o1.opEquals(o2)) of type int to bool" But: ==== bool fn2() { return 1; } ==== compile ok! DMD 1.039 |
February 10, 2009 Re: error in return statement | ||||
---|---|---|---|---|
| ||||
Posted in reply to zorran | "zorran" wrote
> possibly error in return statement:
> ====
> bool fn1(Object o1, Object o2 ) {
> return o1.opEquals(o2); // opEquals return int
> }
> ====
>
> compiler writes:
> "Error: cannot implicitly convert expression (o1.opEquals(o2)) of type int
> to bool"
>
> But:
> ====
> bool fn2() {
> return 1;
> }
> ====
> compile ok!
>
> DMD 1.039
It's because you are using a literal. A literal '1' is sort of magic as it can be interpreted as many different types, including int, float, bool, etc.
BTW, in DMD 2, Object.opEquals() returns bool (long-standing bug). Don't think it's planned for D1 however.
-Steve
|
February 10, 2009 Re: error in return statement | ||||
---|---|---|---|---|
| ||||
Posted in reply to zorran | On Tue, Feb 10, 2009 at 11:16 AM, zorran <zorran@tut.by> wrote: > possibly error in return statement: > ==== > bool fn1(Object o1, Object o2 ) { > return o1.opEquals(o2); // opEquals return int > } > ==== > > compiler writes: > "Error: cannot implicitly convert expression (o1.opEquals(o2)) of type int to bool" > > But: > ==== > bool fn2() { > return 1; > } > ==== > compile ok! > > DMD 1.039 > In http://www.digitalmars.com/d/1.0/type.html, the bool section: "The numeric literals 0 and 1 can be implicitly converted to the bool values false and true, respectively. " That's what's happening with fn2. If you did: bool fn2() { int x = 1; return x; } you would also get an error. |
February 13, 2009 Re: error in return statement | ||||
---|---|---|---|---|
| ||||
Posted in reply to zorran | zorran wrote:
> possibly error in return statement:
> ====
> bool fn1(Object o1, Object o2 ) {
> return o1.opEquals(o2); // opEquals return int
> }
> ====
>
> compiler writes:
> "Error: cannot implicitly convert expression (o1.opEquals(o2)) of type int to bool"
>
> But:
> ====
> bool fn2() {
> return 1;
> }
> ====
> compile ok!
>
> DMD 1.039
A quick way around this is the !! "operator", i.e. double negotiation. "return !!o1.opEquals(o2); "
It should be clear how this works. If not, try to think of !!a as !(!(a)).
|
Copyright © 1999-2021 by the D Language Foundation