# C++ conditional ternary operators, evaluate more than one expression

Even since I have learned about C++’s conditional ternary operators I have been using the heck out of them to create short code where if / then loops would have been before.

The operator is the question mark, ?, and you use it like so:

condition ? result1 : result2


The equivalent if / then is:

if (condition == true){
result1;
} else {
result2;
}


There’s more detail at www.cplusplus.com, at the ‘conditional ternary operators’ section.

Something I do very frequently: iterating through a loop, load an image, do things with it, need to record some things. In this case it is the min / max of rows / cols of some features.

im.rows > max_rows ? max_rows = im.rows : 0;
im.rows < min_rows ? min_rows = im.rows : 0;

im.cols > max_cols ? max_cols = im.cols : 0;
im.cols < min_cols ? min_cols = im.cols : 0;


I do this kind of thing a lot. There is no result2, or else to my conditional, so I just put 0.

But, I wanted to alter this code to record the index that triggered the update of the min / max values. In other words, I wanted two expressions instead of one to be evaluated.

It turns out I can do this with the comma operator! (The next operator down at www.cplusplus.com from the conditional ternary operator.) Where one expression is expected, join two together with a comma and enclose with parentheses.

So I can alter my four lines as follows:

 im.rows > max_rows ? (max_rows = im.rows, max_row_index = i) : 0;
im.rows < min_rows ? (min_rows = im.rows, min_row_index = i) : 0;

im.cols > max_cols ? (max_cols = im.cols, max_col_index = i) : 0;
im.cols < min_cols ? (min_cols = im.cols, min_col_index = i) : 0;


© Amy Tabb 2018 - 2021. All rights reserved. The contents of this site reflect my personal perspectives and not those of any other entity.