Search code examples
c++pointerscharimplicit-conversionstring-literals

Comparison between pointer and integer in string class - C++


I'm new to C++.

string str = "WWWHBBB";
if(str[mid] == "H" && str[0] != "W") return; // corrected after comments for second operand

The above line with if condition gives me an error.

Comparison between pointer and integer ('std::__1::basic_string, std::__1::allocator >::value_type' (aka 'char') and 'const char *')

I have searched the internet enough to know that array style access is fine in strings. Error basically is pointing out comparison about pointer and integer. Really? I thought I was comparing character H to another character in string str.

I tried if str[mid] really returns an iterator I should do *str[mid]. Nah! Didn't work either.


Solution

  • In the expression of the if statement

     if(str[mid] == "H" && str[mid] != "W") return;
    

    the string literals "H" and "W" that have the type const char[2] are implicitly converted to pointers to their first characters of the type const char *.

    So you are trying to compare a character returned by the expression str[mid] with a pointer.

    Instead of the string literals you need to use character literals like to compare characters

     if(str[mid] == 'H' && str[mid] != 'W') return;
    

    You could also write like

     if(str[mid] == *"H" && str[mid] != *"W") return;
    

    or

     if(str[mid] == "H"[0] && str[mid] != "W"[0]) return;
    

    dereferencing the pointers but this will be confusing

    Pay attention to that if str[mid] == 'H' then the second operand will always yield true. So it is enough to write

     if( str[mid] == 'H' ) return;