Baruch
Baruch

Reputation: 21508

A if A else B but evaluate A only once

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

Upvotes: 4

Views: 159

Answers (2)

Thomas Caissard
Thomas Caissard

Reputation: 866

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.

Upvotes: 5

lxop
lxop

Reputation: 8595

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.

Upvotes: 2

Related Questions