3

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,742
  • 1
  • 8
  • 22
prve17
  • 51
  • 3

3 Answers3

8

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"s, "D"s) << endl;

To pass std::strings instead of passing the addresses of the string literals.

See string literal operator

Demo

Or use characters instead of using string literals i.e 'C' and 'D' and in that case, X will be inferred as char.

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

asmmo
  • 6,742
  • 1
  • 8
  • 22
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
  • 200,579
  • 13
  • 144
  • 260
2

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;
}
Ayxan Haqverdili
  • 23,309
  • 5
  • 37
  • 74