2

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.

11
  • 4
    I rarely see the second one in the wild. Mostly the first. The compiler should convert both to code resembling the second. Commented Jul 13, 2016 at 5:43
  • 4
    int depth = s.size(); would be enough here. Commented Jul 13, 2016 at 5:44
  • 7
    depth = std::max<int>(depth, s.size()) Commented Jul 13, 2016 at 5:46
  • 4
    Not related, but depth shoutd be a std::size_t to have the same type as s.size(). Commented Jul 13, 2016 at 5:46
  • 7
    The second form violates several common style-guide rules, such as using an expression as a statement, and inner expressions with side-effects. And obscurity. Not that style guides are infallible. Commented Jul 13, 2016 at 5:47

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

The first example is more idiomatic than the second. This is what I was looking for.

Note: However, after reading, I agree this is poor use of the operator. A simple if statement works in place of the ternary operator.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.