Comparison of two integer values,

Inspired by the current top answer to this popular question about getting the larger of two values ​​in C # .

Consider a function that takes two integer pointers and returns a pointer. Both pointers can be nullptr

.

const int*  max(const int* a, const int* b);

      

If a or b is nullptr

, return a non-null pointer. If both parameters nullptr

, return nullptr

.

If both valid pointers return max(*a, *b);

.

Currently the most answered C # question is:

int? c = a > b ? a ?? b : b ?? a;

      

Int? represents a null-valued value that is not much different from a pointer.

How can this be expressed in an elegant and idiomatic way in C ++?

My immediate attempt was that

const int* maxp(const int* a, const int* b){
   if (!a) return b;
   if (!b) return a;
   return &std::max(*a, *b); 
}

      

+3


source to share


2 answers


The temptation of the ternary operator is great

const int* maxp(const int *a, const int *b) {
    return a? (b? &std::max(*a, *b) : a) : b;
}

      



but that's because it's funny, not because it's better.

The code in the question is more readable.

+2


source


You have a problem with your code that it returns a pointer to the std :: max output. Taking the exit address of a function tends to be buggy and always tastes bad. This is correct if the function returns a reference to the variable, which will persist as long as the pointer is held.

I would replace the last line of your function with a simple if statement:

if (*a > *b) return a;
else return b;

      



This way you will always return one of the pointers that were entered into your function.

PS I looked at the standard relatively std::max

and didn't understand it. But ultimately, even if your code works (because it std::max

returns a link), it's best not to take the address of the specified link.

PPS Avoiding the ternary operator is by far the best in terms of clarity. The rest of your function is fine.

-2


source







All Articles