The ternary operator (the question mark and colon in the expression a ? b: c) is a tricky one. It’s use is relatively uncommon, but it’s present in many programming languages, and sometimes it drastically simplifies a conditional assignment. I bring it up because it was in the first version I saw of the GAA objective function, and it was doing something it shouldn’t have been. Before I took up the GAA problem, some of the work involved allowing a 3 percent constraint violation. This was still present in the objective function when I got my hands on it, although we no longer wanted to allow a 3 percent constraint violation.
Here’s what it looked like:
constr = CV_TOTAL > 0.03 ? CV_TOTAL : 0.0;
What it does is assign CV_TOTAL to constr only if CV_TOTAL is greater than 0.03, and otherwise it assigns 0 to constr. It works this way because in general, the expression a ? b : c evaluates to b if a is true, and to c if a is false. So writing d = a ? b : c is a shorthand way of saying, “assign b to d if a is true, and assign c to d if a is false.” And what it does in this case is allow 3% constraint violation.
My advice: there’s nothing wrong with using the ternary operator, but don’t be stingy with your comments. Writing it like this could save you a lot of time:
constr = CV_TOTAL > 0.03 ? CV_TOTAL : 0.0; // allow 3% constraint violation!
Of the languages that I’ve used, the ternary operator shows up in this form in C, C++, Java, and Ruby.