Inspired by the current top answer to this popular question concerning getting the larger of two values in C#.
Consider a function that accepts two integer pointers, and returns a pointer. Both pointers might be nullptr.
const int* max(const int* a, const int* b);
If a or b is a nullptr return the non-null pointer. If both are nullptr, return nullptr.
If both are valid pointers return max(*a, *b);.
The currently most upvoted answer for the C# question is
int? c = a > b ? a ?? b : b ?? a;
int? represents a nullable value, not unlike a pointer.
How can this be expressed in an elegant and idiomatic fashion in c++?
My immediate attempt was along the lines of
const int* maxp(const int* a, const int* b){
if (!a) return b;
if (!b) return a;
return &std::max(*a, *b);
}
The temptation of the ternary operator is big
const int* maxp(const int *a, const int *b) {
return a? (b? &std::max(*a, *b) : a) : b;
}
but it's because it's funny, not because it's better.
The code in the question is more readable.
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