View Single Post
  #2  
Old 10-02-2011, 12:19 PM
magicode's Avatar
magicode magicode is offline
Senior Member
VEX # 4542
 
Join Date: Sep 2010
Posts: 608
Re: RobotC programming tips

I guess I'll start off with something simple: ternary operators. Obviously this isn't specifically for ROBOTC, but many beginners don't know about it. I find it to be very useful in shortening code. A ternary operation will look something like this:
Code:
value = (boolean statement) ? (value if statement is true) : (value if statement is false);
So in a real world example:
Code:
motor[port2] = abs(vexRT[Ch2]) > 10 ? vexRT[Ch2] : 0;
In contrast to this, the if else statement would look like this:
Code:
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.
Code:
motor[port2] = vexRT[Ch2] > 10 ? vexRT[Ch2] : vexRT[Ch2 < -10 ? (vexRT[Ch2] / 2) : 0;
__________________
It's not a bug, it's a feature.
Reply With Quote