Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A if A else B but evaluate A only once

Tags:

c++

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

like image 794
Baruch Avatar asked Mar 02 '23 13:03

Baruch


2 Answers

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.

like image 141
Thomas Caissard Avatar answered Mar 15 '23 04:03

Thomas Caissard


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.

like image 32
lxop Avatar answered Mar 15 '23 05:03

lxop