Hi, so in RobotC, I used ternary operators to give my drive base a certain threshold. It looked like this:
motor[leftdrive1] = abs(vexRT[Ch3]) > 10 ? -vexRT[Ch3] : 0;
motor[leftdrive2] = abs(vexRT[Ch3]) > 10 ? -vexRT[Ch3] : 0;
motor[rightdrive1] = abs(vexRT[Ch2]) > 10 ? -vexRT[Ch2] : 0;
motor[rightdrive2] = abs(vexRT[Ch2]) > 10 ? -vexRT[Ch2] : 0;
I’m new to c++, so can someone explain how to do something similar in VCS?
Normal c++ is a superset of c, so in principle any valid c program is also a valid c++ program. Thus, ternary operators are supported in ‘normal’ c++. I don’t own any v5 hardware and haven’t written very much VCS c++, so I wasn’t able to definitively confirm that vex c++ supports ternary ops. However, VCS’s syntax highlighting appeared to highlight things correctly when I wrote some statements using ternary ops. So, it looks like ternary operators should be supported.
In case VCS c++ doesn’t support ternary operators, any statement made using ternary operators can be equivalently written as an if-else statement like this:
a = condition ? trueValue : falseValue;
is equivalent to
a = trueValue;
a = falseValue;
Of course, this isn’t as concise as using ternary operators, but it does provide equivalent functionality.
(Side note: ternary operators are cool and fun, but it’s easy to get carried away. I once used several layers of nested ternary operators to write a one-line function to find the median of 3 integers. I felt like a ninja at the time, but trying to debug
(a > b) ? ((b > c) ? b : ((a < c) ? a : c)) : ((b < c) ? b : ((a < c) ? c : a))
the next day when some bugs came up was a real pain.)