When dealing with functions that have a signature like:
bool getValue(int parameter, int *out)
where they write their result to the memory addressed by *out
and return a boolean indicating whether the function succeeded, I'm considering using the following pattern to chain several of these functions together in an order of priority:
int result = 0;
bool success = getValue(param1, &result) || getValue(param2, &result) ||
getAnotherValue(param3, &result);
if (success) {
// do something with result
} else {
// handle error
}
I'm thinking it would be a more succinct and pretty version of this:
int result = 0;
bool success = getValue(param1, &result);
if (!success) {
success = getValue(param2, &result);
if (!success) {
success = getAnotherValue(param3, &result);
}
}
if (success) {
// do something with result
} else {
// handle error
}
As I understand, if any one of the functions succeed then the ||
operator will short circuit and the remaining functions won't be called, leaving the desired output in result
.
Is this a safe pattern to use, especially in code that is cross-platform and will be compiled using different compilers (e.g. clang, gcc, and msvc?)
The second piece of code is assuredly equivalent to the first piece of code, if that's what you're asking.
Short-circuiting means the "unused" expressions on the right of a non-overloaded ||
aren't evaluated, which means the functions aren't called, which means &result
isn't touched again.
Any compiler not abiding by these semantics is not just flagrantly non-compliant to the C++ standard, but unheard of.
However, this is not the case for an overloaded ||
. As a result, we're encouraged not to make any.