Is there some convenient way to write the expression
val = A ? A : B;
where A would only be evaluated once? Or is this the best (it is just ugly):
auto const& temp = A;
val = temp ? temp : B;
To clarify, A and B are not of type bool
Use the Elvis operator, which is supported in some C++ compilers:
val = A ?: B;
See Conditionals with Omitted Operands in gcc's documentation.
EDIT: This is not portable, and won't work in MSVC, for example. It works in gcc since 2.95.3 (March 2001), and on clang since 3.0.0.
Why not just
val = A || B;
?
That will make use of shortcutting to use A if it is true, otherwise B.
Note that this will only work if the values in question here are boolean; see the notes in the comments below from @ApproachingDarknessFish.
For non-booleans, if you want standard C++ then you will probably have to use your suggested ugly option.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With