If you’re new to RobotC and searching for sample code or explanations, you will frequently run into statements that look very confusing, involving a question-mark (?) and a colon (:), such as:

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

If you’re like me in the early stages of learning RobotC, at this point your eyes glaze over and you think something like, “This is too complicated, I’ll look for another answer somewhere else.”

It turns out that these statements are actually pretty cool. This structure is called a “ternary” operator (ternary = comprised of 3 parts), and it is a way of having an if-else statement all in one line.

This particular ternary sample is a way of connecting motor2 to joystick Channel 3, including a deadband area of ±10 (in RobotC “abs” refers to “absolute value”). What the above sample translates to is:

motor
power
= 
Condition
to check
what to do
if true
what to do
if false
;
motor[port2]  
= 
abs(vexRT[Ch3])  > 10
vexRT[Ch3]
0
;
motor[port2]  
= 
is Ch3 >
deadband
set motor to
Ch3 value
set motor
to 0
;

Use as Appropriate

For kids who are programming novices, I would not recommend this style of writing instructions, as it can make it difficult to find errors when there’s so much going on in just one line of code (and then throw in multiple programmers at varying skill levels, and … probably a mess). But that doesn’t mean that they (and you) shouldn’t know how to read this code so that you can learn from the vast quantities of information and sample code available on the VEX Forum and the RobotC Forum.

For kids who already have some programming experience under their belts, this can be a great next step in sophistication, especially when your overall program is becoming more complex and, therefore, longer. Using ternary commands can reduce the overall length of the program, so instead of 7 lines on the screen like this:

   if (abs(vexRT[Ch3]) > 10) {
      motor[port2] = vexRT[Ch3];
   }

   else {
      motor[port2] = 0;
   }

You get 1 line of code like this.

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

That Question Mark

For some reason the question mark throws me off pretty much every time I read one of these ternary statements, because my brain wants to think of a question mark indicating a comparison, somehow comparing “vexRT[Ch3] > 10” and “vexRT[Ch3].” But of course that makes no sense, hence the eyes-glazing-over thing I mentioned at the start. If you also find this part confusing, train your mind to attach the question mark to the first part, the comparison statement: “Is Ch3 greater than 10?” Followed by “yes : no” (what to do if true : what to do if false).

♦        ♦        ♦

Hope this helps. In short, no one *needs* to use this ternary programming structure, but *everyone* should know how to read it.

Share this post: