Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two integer values pointed to [closed]

Tags:

c++

pointers

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); 
}
like image 806
Captain Giraffe Avatar asked Aug 30 '26 10:08

Captain Giraffe


1 Answers

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.

like image 126
6502 Avatar answered Sep 01 '26 04:09

6502



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!