4

Can someone explain, why the output is "C" in this code?

#include <iostream>
using namespace std;
template<class X>
X maximum(X a,X b)
{
    if(a > b)
        return a;
    else 
        return b;
}

int main() {
    cout << maximum("C","D") << endl;
}
asmmo
  • 6,922
  • 1
  • 11
  • 25
prve17
  • 61
  • 3

3 Answers3

9

Note that in your case the type X will be inferred as const char*, hence you are comparing two const char *s i.e. the addresses of the two string literals.

If you want to get the expected result, use something like the following

cout << maximum("C"sv, "D"sv) << endl;
// or
cout << maximum<string_view>("C", "D") << endl;

This compares two std::string_views, which is a lexicographical comparison, not a pointer comparison.

See std::string_view comparison operators, and see demo at Compiler Explorer.

Alternatively, use characters instead of using string literals i.e 'C' and 'D'. In that case, X will be deduced to char.


See also Why is "using namespace std;" considered bad practice?

Jan Schultke
  • 17,446
  • 6
  • 47
  • 96
asmmo
  • 6,922
  • 1
  • 11
  • 25
2

When you use maximum("C","D"), the template parameter is char const*. You end up comparing two pointers. There is no guarantee which pointer will be greater. You have indeterminate behavior.

If you want to compare the string "C" and string "D", you can use:

cout << maximum(std::string("C"), std::string("D")) << endl; // or
cout << maximum("C"s, "D"s) << endl;                         // or
cout << maximum<std::string>("C", "D");

If you want compare just the characters C and D, you should use

cout << maximum('C', 'D') << endl;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
1

If you want this to work for cstring-literals also, add a specialization.

#include <cstring>

template<class X>
X maximum(X a, X b)
{
    return a > b ? a : b; 
}

template<>
char const* maximum<char const*>(char const* a, char const* b)
{
    return std::strcmp(a, b) > 0 ? a : b;
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93