prve17
prve17

Reputation: 59

Why is the output of the maximum of two string literals wrong?

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;
}

Upvotes: 3

Views: 356

Answers (3)

Aykhan Hagverdili
Aykhan Hagverdili

Reputation: 29975

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

#include <cstring>

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

char const* maximum(char const* a, char const* b)
{
    return std::strcmp(a, b) > 0 ? a : b;
}

char* maximum(char* a, char* b)
{
    return std::strcmp(a, b) > 0 ? a : b;
}

Upvotes: 1

asmmo
asmmo

Reputation: 7100

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?

Upvotes: 9

R Sahu
R Sahu

Reputation: 206577

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;

Upvotes: 2

Related Questions