Search code examples
c++conditional-statementsternary

c++ ternary operator use


I am working in C++. I have two statements involving the ternary operator.

std::stack<Node*> s;
int depth = 0;
/*modify depth integer and stack size, based on height of BST*/
depth = s.size() > depth ? s.size() : depth;

std::stack<Node*> s;
int depth = 0;
/*modify depth integer and stack size, based on height of BST*/
s.size() > depth ? depth = s.size() : depth = depth;

My question is this: Is there a standard way to assign a variable with the ternary operator? Is one of these forms more efficient, concise, or better than the other?

The second example seems to be more redundant than the first.

Edit: added comment that both s and depth are modified before the ternary operator.


Solution

  • The ternary expression is primarily used for the value that it produces. It's possible to abuse it and only use its side effects, but that kind of construct is better left to an ordinary if statement. So the first example is an idiomatic use of the ternary expression (although, as the comments point out, probably inappropriate in this particular case), while the second example is not.