Thursday, September 4, 2008

AHK - The Ternary Operator ( ?: )

This is a short faq/guide about the use of the Ternary Operator in AHK. If you think of anything I should add, please post a comment.
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
In English, this can be written as "If X is true, set Var to 1. Else, set Var to 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
Could be written as
If (X == 1)
Var := 1
Else {
If (X == 2)
Var := 2
Else
Var := 0
}
And as a ternary operator, it would look like this:
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: