Tern
Syntax
Assignment Variable = Tern (Param1 Condition Param2, ValueIfTrue, ValueIfFalse)
Overview
The Tern function is a form of Ternary Operator and has the same mechanism as a C compiler's '?' directive. If the comparison between Param1 and Param2 is true, then the assignment Variable will be loaded with ValueIfTrue, otherwise it will be loaded with ValueIfFalse. It is the equivalent of:
If Param1 condition Param2 Then
Variable = ValueIfTrue
Else
Variable = ValueIfFalse
EndIf
But it is in a single line of code and the asm code it produces is the same as it is if the comparison was written as above.
Parameters
Param1 can be any valid variable, constant, expression or procedure call that will be compared to Param2. Param2 can be any valid variable, constant, expression or procedure call that will be compared to Param1. Condition is a standard set of comparison characters as found in the If command. They can be <, >, <=, >=, <> or =. ValueIfTrue can be any valid variable, constant or procedure call that will be loaded into the assignment Variable if the comparison between Param1 and Param2 is true. ValueIfFalse can be any valid variable, constant or procedure call that will be loaded into the assignment Variable if the comparison between Param1 and Param2 is false. Assignment Variable can be any valid variable type.
Example
' Load a bit with a 1 or a 0 depending on the state of a variable
'
Device = 24FJ64GA002
' Select the device to compile for
Declare Xtal = 16
Declare Hserial_Baud = 9600 ' USART1 Baud rate
Declare Hrsout1_Pin = PORTB.14 ' Select the pin for TX with USART1
Dim Wordin as Word
' Create an unsigned Word variable
Dim Bitout as Bit
' Create a Bit variable
Wordin = 1024
'
' Load Bitout with 1 if Wordin holds less than 1000
'
Bitout = Tern(Wordin < 1000, 1, 0)
HrsoutLn "Bitout = ", Dec Bitout
'
' Load Bitout with 1 if Wordin holds greater than 1000
'
Bitout = Tern(Wordin > 1000, 1, 0)
HrsoutLn "Bitout = ", Dec Bitout