Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing std::string and C-style string literals

Suppose I have the following code:

#include <iostream>
#include <string>
#include <iomanip>
using namespace std; // or std::

int main()
{
    string s1{ "Apple" };
    cout << boolalpha;
    cout << (s1 == "Apple") << endl; //true
}

My question is: How does the system check between these two? s1 is an object while "Apple" is a C-style string literal.

As far as I know, different data types cannot be compared. What am I missing here?

like image 360
Aditya Prakash Avatar asked Dec 26 '19 15:12

Aditya Prakash


People also ask

What is the difference between C style strings and C++ style strings?

Neither C or C++ have a default built-in string type. C-strings are simply implemented as a char array which is terminated by a null character (aka 0 ). This last part of the definition is important: all C-strings are char arrays, but not all char arrays are c-strings.

Can you compare string literals in C?

You can't compare strings with == in C. For C, strings are just (zero-terminated) arrays, so you need to use string functions to compare them. See the man page for strcmp() and strncmp(). If you want to compare a character you need to compare to a character, not a string.

How do you compare string literals?

To compare string literals, still use the equality and relational operators, but for objects of the string class, and not for const char*s. Using the operators for const char*s compares the pointers, and not the string literals.

What is the difference between string and std::string in C++?

There is no functionality difference between string and std::string because they're the same type.


1 Answers

It is because of the following compare operator defined for std::string

template< class CharT, class Traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs, const CharT* rhs );  // Overload (7)

This allows the comparison between std::string and the const char*. Thus the magic!


Stealing the @Pete Becker 's comment:

"For completeness, if this overload did not exist, the comparison would still work; The compiler would construct a temporary object of type std::string from the C-style string and compare the two std::string objects, using the first overload of operator==

template< class CharT, class Traits, class Alloc >
bool operator==( const basic_string<CharT,Traits,Alloc>& lhs,
                 const basic_string<CharT,Traits,Alloc>& rhs );   // Overload (1)

Which is why this operator(i.e. overload 7) is there: it eliminates the need for that temporary object and the overhead involved in creating and destroying it."

like image 198
JeJo Avatar answered Sep 20 '22 01:09

JeJo