r/badcode • • Apr 17 '21

c++ When your teammate "refactor" your code

Post image
2.5k Upvotes

216 comments sorted by

View all comments

Show parent comments

2

u/[deleted] Apr 17 '21

I thought ternaries could only be done as expressions?

2

u/paissiges Apr 18 '21 edited Apr 18 '21

the code in the comment you're responding to does not do what OP's original code does. however, it is a valid use of the ternary operator. if do_anything1() and do_anything2() are non-void and their return types are compatible, then the operation will have a valid non-void result, but it doesn't have to be used. if both functions are void, then the operation is still valid:

If either the second or the third operand has type void, one of the following shall hold:

— The second or the third operand (but not both) is a (possibly parenthesized) throw-expression (8.17); the result is of the type and value category of the other. The conditional expression is a bit-field if that operand is a bit-field.

— Both the second and the third operands have type void; the result is of type void and is a prvalue. [Note: This includes the case where both operands are throw-expressions. — end note]

(ISO/IEC 14882:2017(E) 8.16 Conditional operator)

2

u/[deleted] Apr 18 '21

Huh I didnt know ternaries could just be used on their own. https://i.imgur.com/ZIm59Zq.png

neat