Page 1 of 1

Incorrect behavior of ?: operator

Posted: Fri Jun 15, 2012 7:12 am
by Rado1
I usually use the ?: operator for assignments without problems, but this particular situation surprised me.

Why the ?: expression below returns strange numbers, eg., 1079134336 for Level==2 and NumberOfBonuses > 0? Level and NumberOfBonuses are integer variables, SpawnBonusTimer is a Timer. I tried also "if" version, which works as expected; returns, e.g., 4 for level 2. See the code snippets below.

Code: Select all

// incorrect results
SpawnBonusTimer.Interval = (NumberOfBonuses < 1) ? 0 : random(1, 0.3) * (8.0 / Level);

Code: Select all

// correct results
if(NumberOfBonuses < 1) SpawnBonusTimer.Interval = 0;
else SpawnBonusTimer.Interval = random(1, 0.3) * (8.0 / Level);
Either I overlooked something or there's a bug in the ?: operator.

Posted: Fri Jun 15, 2012 11:45 am
by VilleK
It's both a bug and a known problem with parsing the "?" operator in C-style languages. The bug in this case is that it incorrectly interprets the float as an int and I'll change the compiler so that this won't happen.

The compiler has a problem to determine the type of the "?" expression because the "true" part is an int and the "false" part is a float. If you force both parts to float it should work "? 0f : "... (notice the "f").

Posted: Fri Jun 15, 2012 11:56 am
by Rado1
Thanks Ville. I was not aware of this issue before. Every day we learn something new...

Posted: Fri Jun 15, 2012 12:05 pm
by Kjell
:?

Please don't fix this! It's the only way / hack to cast floats to ints ( and vice versa ).

K

Posted: Fri Jun 15, 2012 12:11 pm
by Rado1
What about floor() or ceil() functions? It's not real casting, but can be used instead.

Posted: Fri Jun 15, 2012 12:29 pm
by Kjell
Hi Rado,

That's converting, I'm talking about the re-interpretation of a bit-pattern.

http://emix8.org/forum/viewtopic.php?t=729

K

Posted: Fri Jun 15, 2012 12:39 pm
by Rado1
I understand now. So, I do think ?: should be fixed; but can be documented better in help.

Posted: Fri Jun 15, 2012 2:24 pm
by VilleK
I had forgotten about that Kjell. Ok I won't fix it for now, but we should have another way of doing the int/float hacks that makes it more obvious just by reading the code what is happening. In C++ there are things like reinterpret_cast for this.

Posted: Fri Jun 15, 2012 2:28 pm
by Kjell
Hej Ville,

That would be the best solution yes :) Being able to use FileMoveData on a integer variable would help as well ( as that is the primary offender I use the ? hack for ).

K