Page 1 of 1

Help understanding ternary statement in py/objcomplex.c

Posted: Fri Feb 03, 2017 10:39 am
by BrendanSimon
I just saw this change in `py/objcomplex.c` (line 225). I have no idea what the ternary statement is supposed to do. Is it a bug or some unusual use of the conditional operator?

Code: Select all

-                if (rhs_imag == 0) {
-                    lhs_real = 1;
+                if (rhs_imag == 0 && rhs_real >= 0) {
+                    lhs_real = 1 ? rhs_real == 0 : 0;
Doesn' the first expression `1` always evaluate to true, then the second expression is always executed?

What is the purpose of the third expression `0` ?

Is this equivalent to `lhs_real = true` or `lhs = false`, depending on the value of rhs_real ?

If so, why wouldn't it be written as: `lhs_real = (rhs == 0) ;

Is this some fancy way of assigning a boolean or an integer (by some magic) ?

And I thought I knew C ?[/color]

Re: Help understanding ternary statement in py/objcomplex.c

Posted: Fri Feb 03, 2017 10:55 am
by deshipu

Re: Help understanding ternary statement in py/objcomplex.c

Posted: Fri Feb 03, 2017 10:58 am
by deshipu
Looking closer, it looks like a bug. Someone probably got confused with Python's "foo = bar if baz else boo" and got this wrong.

Re: Help understanding ternary statement in py/objcomplex.c

Posted: Fri Feb 03, 2017 11:20 am
by BrendanSimon
That's what I thought too -- that it was a Python ternary statement, but then double checked that it was a C file.

But the code I've seen in MicroPython looks very well written, so I assumed it was correct and purposeful (but even the really good programmers are fallible)

I also found this on stackoverflow (trying to find an answer) and it has a similar syntax, but it is about the type returned if both 2nd and 3rd expressions are pointers, which doesn't seem to apply in this case.

http://stackoverflow.com/questions/1409 ... ypecasting

Hopefully it's a bug, as it certainly isn't very clear (at least to me)

Re: Help understanding ternary statement in py/objcomplex.c

Posted: Fri Feb 03, 2017 1:05 pm
by stijn
*edit* not sure if what I wrote was even correct and I can't be bother to lookup the standard rules atm

Re: Help understanding ternary statement in py/objcomplex.c

Posted: Fri Feb 03, 2017 1:22 pm
by pythoncoder
Agreed. It looks like an issue that should be raised on GitHub.

[EDIT]I see it was, a few minutes ago.

Re: Help understanding ternary statement in py/objcomplex.c

Posted: Fri Feb 03, 2017 1:24 pm
by deshipu
I think it was supposed to be:

Code: Select all

if (rhs_real == 0) {
    lhs_real = 1;
} else {
    lhs_real = 0;
}
Which could of course be written much shorter:

Code: Select all

lhs_real = !rhs_real;

Re: Help understanding ternary statement in py/objcomplex.c

Posted: Fri Feb 03, 2017 1:49 pm
by stijn