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; } 
2
  • lexicographical comparison is happening here. Commented Oct 17, 2020 at 8:21
  • 2
    @BuildSucceeded no, it's not. It's just comparing 2 unrelated pointers Commented Oct 17, 2020 at 8:53

3 Answers 3

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?

Sign up to request clarification or add additional context in comments.

Comments

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; 

4 Comments

or 'C' and 'D' if author wanted to compare just chars
@ŁukaszŚlusarczyk, indeed.
For comparing string literals, consider using maximum<std::string>(“C”, “D”), or maximum(“C”s, “D”s) like in asmmo’s answer.
*unspecified behaviour
1

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.