Page 1 of 1

Ternary operator in calculation block?

Posted: Thu Mar 14, 2024 10:29 pm
by MJU20
Ternary operator in calculation block?
Wouldn't that be a hoot?

Code: Select all

val2 = (val1 < 20)?3:2
https://en.wikipedia.org/wiki/Ternary_c ... l_operator

Re: Ternary operator in calculation block?

Posted: Thu Mar 14, 2024 10:54 pm
by kersing
Yep, that’s what I thought a couple of years ago as well. Got declined as being unreadable for novice users. Hopefully it will be reconsidered…

Re: Ternary operator in calculation block?

Posted: Fri Mar 15, 2024 6:18 am
by mnfisher
One trick I use a lot - allows an imitation of the ternary operator in a lot of cases.

Boolean operations return 1 for true and 0 for false.

So use:

.v1 = (.v2 < 20) + 2. // 3 if v2 is < 20 else 2

.flag = (.v == 10) // flag true if v = 10

Martin

Re: Ternary operator in calculation block?

Posted: Fri Mar 15, 2024 9:11 am
by kersing
Thanks for the hint, however strictly speaking false is zero and true might be any value not zero, so this working depends compiler/controller (and a bit of luck?)

Re: Ternary operator in calculation block?

Posted: Fri Mar 15, 2024 9:21 am
by mnfisher
True - but I've not had any issues so far. Also use if(.x) rather than if(.x !=0 ) - would be interesting to know if it actually saves any memory / or time. Must do a test...

It could come back to bite me someday :shock:

Martin

Re: Ternary operator in calculation block?

Posted: Fri Mar 15, 2024 9:37 am
by kersing
Any halfway decent compiler should optimize the expression, BTW, you probably don’t want to include a space between the exclamation mark and the equal sign as it should throw a syntax error. The correct syntax is if ( .x != 0 )
And in flowcode you can use <> which is easier on the eyes for novice programmers…

Re: Ternary operator in calculation block?

Posted: Fri Mar 15, 2024 10:01 am
by mnfisher
Autocorrect on my phone..

I read it as not(!) equal - nice that either works...

Re: Ternary operator in calculation block?

Posted: Fri Mar 15, 2024 5:00 pm
by MJU20
Thanks guys for this input.

The trick from mnfisher I will remember, together with the remark that "false is zero and true might be any value not zero"..

As a non programmer readability is necessary for me, so I mostly use <>.
Flowcode is a nice program to not need to read code so the simpeler it gets the better.
But for an example like val2 = (val1 < 20)?3:2 there is a lot of commands needed..

I will start a Onenote to keep these tricks for me to remember.