The following base code is part of a quite large procedure:
int x = foo();
if (x == 0) x = bar();
x
is not modified anywhere else, so I'd can do:
const int x = foo() == 0 ? bar() : foo();
But foo()
is a very expensive and complex function so I can't call it twice due to performance and to the fact that it may generate a race condition and therefore obtain different values (it may involve reading external resources).
I'd like to make code as readable and, if possible, short, as possible. One option is to:
const int foo_ = foo(), x = foo_ == 0 ? bar() : foo_;
I'd like to avoid that kind of temporal variable since it may confuse the reader and, as mentioned above, foo()
may depend on external resources, so using foo_
as a cached value in the rest of the code is not valid.
I'm posting the solution I'm using right now but I'd like to know if there are better options. Thanks in advance!
Aucun commentaire:
Enregistrer un commentaire