Difference between revisions of "Tertiary operators"

From ROBOTC API Guide
Jump to: navigation, search
 
(2 intermediate revisions by one user not shown)
Line 1: Line 1:
{{DISPLAYTITLE: Tertiary Operators}}
+
{{DISPLAYTITLE: Ternary Operators}}
 
<yambe:breadcrumb self="Tertiary Operators">Programming_Tips_Tricks|Programming Tips Tricks</yambe:breadcrumb>
 
<yambe:breadcrumb self="Tertiary Operators">Programming_Tips_Tricks|Programming Tips Tricks</yambe:breadcrumb>
 
<br />
 
<br />
Line 7: Line 7:
 
|-
 
|-
 
|<syntaxhighlight lang="ROBOTC">
 
|<syntaxhighlight lang="ROBOTC">
value = (boolean statement) ? (value if statement is true) : (value if statement is false);
+
value = ( /*boolean statement*/ ) ? ( /*value if statement is true*/ ) : ( /*value if statement is false*/ );
 
</syntaxhighlight>
 
</syntaxhighlight>
 
|}<br />
 
|}<br />

Latest revision as of 15:59, 10 August 2012

General ProgrammingProgramming Tips Tricks → Tertiary Operators


A ternary operation will look something like this:

value = ( /*boolean statement*/ ) ? ( /*value if statement is true*/ ) : ( /*value if statement is false*/ );

So in a real world example:

motor[port2] = abs(vexRT[Ch2]) > 10 ? vexRT[Ch2] : 0;

In contrast to this, the if else statement would look like this:

if(abs(vexRT[Ch2]) > 10)){
  motor[port2] = vexRT[Ch2];
}else{
  motor[port2] = 0;
}

You can also nest ternary statements. For example, if you wanted to say: move the motor forward at the value of the joystick if it is positive and above the threshold value, but move the motor backward at 1/2 joystick value of it is negative and below the threshold value, then you can nest the ternary statements to make a if else if else statement.

motor[port2] = vexRT[Ch2] > 10 ? vexRT[Ch2] : vexRT[Ch2 < -10 ? (vexRT[Ch2] / 2) : 0;

This tip was posted by magicode over at http://www.vexforum.com/showpost.php?p=220747&postcount=2.