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; } 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; } 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?
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; maximum<std::string>(“C”, “D”), or maximum(“C”s, “D”s) like in asmmo’s answer.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; }