Enjoy :)
1.) What is a Ternary Operator?
A ternary operator is like a shortened if-else statement, that can be used in a one-line expression. For example:
Var := X ? 1 : 0
2.) What's the point?
Ternary operators can make code more readable (or sometimes less), and much more compact. For example, would you rather use the previous code or this in your really long script?
If (X)
Var := 1
Else
Var := 0
3.) Can I do if-elseif-else expressions too?
Sadly, no you can't. There is a rather easy workaround for this, but code readability goes downhill fast. The workaround is simply nesting the if statements, for example:
If (X == 1)
Var := 1
Else If (X == 2)
Var := 2
Else
Var := 0
If (X == 1)
Var := 1
Else {
If (X == 2)
Var := 2
Else
Var := 0
}
Var := X == 1 ? 1 : (X == 2 ? 2 : 0)
4.) Does the ternary operator lower speed/performance?
In some cases, it can, but usually by less than 10µs. What does this mean? Nobody but your computer will notice, and it just barely will.
[VxE]'s := guide ? ( to the ternary ) : ( operator ), Ternary Operator Documentation
No comments:
Post a Comment