pcldev
pcldev

Reputation: 5

Strange behaviour in C++

template <typename T> T& larger(T& a, T& b)
{
    return (a>b?a:b);
}


 std::string first {"vv"};
 std::string second {"That is the question in californian"};


 int main(){
 std::cout << larger(first,second) << std::endl;
 }

This should return [if a greater than b , then a , else b ]; but it returns a for me .("vv") What went wrong here >

Upvotes: 0

Views: 105

Answers (2)

Divij Jain
Divij Jain

Reputation: 113

The operator > and < compares both the strings not based upon the length but based on lexicographic order i.e. ASCII values.

Upvotes: 0

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 2914

operator< compares lexicographically for std::string. This means that it compares character by character, starting from the first, and only if they are equal, it compares the next one.

As you can easily verify, it holds that 'v' > 'T'. That is because lowercase letters come after uppercase letters in ASCII encoding.

Upvotes: 5

Related Questions