Bug: var v1=0; var v2=0.764; bool res=v1.equals(v2); res is true, when I expected false

The other way around, i.e.

var v1 = 0; var v2 = 0.764;  bool res = v2.equals(v1); res is false, as should be expected.

I can imagine what is going on, it is going with the type of the first var, which is int, and then casts the second var to the type of the first, getting again 0.

If I instead run v1 = 0; v2 = 2.764; res = v1.equals(v2);

res is false, so the above explanation seems likely.

In res = v2.equals(v1);

The int is instead cast to double, so no information is lost, and the comparison is false in all cases as it should be.

 

I doubt this is desired behaviour since, correct me if I'm wrong, ==, or equals, should be symmetric, i.e. a==b and b==a should give the same result, no?

 

The juce version is not fresh today, but I updated only 2-3 days ago.

I searched for var and equals and found nothing related to this, sorry if I've missed old posts already mentioning the above.

 

I don't think equal tests will be symmetric if there are casts involved, no. It seems like a var will always involve casts.

If you cast both vars to the same, you should get the result you expect.

Bruce

That's the thing though, are you supposed to constantly check what value type ends up in a var? Isn't the whole use of vars that they can hold any variable type?

If we're constantly supposed to cast to different types before comparing, there's no need/place for a function like var::equals() at all, in fact its existence is just confusing, since it does the casts in the shadows!

In fact if you have to cast, why not just use the test for equality of the target type? If you first have to cast to double, there's already perfectly adequate code in C++ for comparing doubles, no?

What I find is confusing is that this issue is masked and the only way to find it out is to trace a bug to it.

Sure, now I solved it by writing if( (v1.equals(v2)==false) || (v2.equals(v1)==false) ) {}, but for a programmer that doesn't know this happens, any use of equals becomes a tricky to find bug. I know it took me a couple of hours to trace my bugs to this.

In fact, in C++, comparing an int = 0 with a double = 0.764 is symmetric:

 

int v1 = 0;
double v2 = 0.764;
bool res = v1 == v2;
bool res2 = v2 == v1;

 

res & res2 are both false, I ran this in visual studio 2010....

Thanks very much - good catch! I've sorted this out now, and added a unit test to check it too.