0

ISO C++ forbids comparison between pointer and integer [-fpermissive]

      if(S[i] == "#")
                 ^~~ 
#include <iostream>
using namespace std;

int main() {
    string S = "a#b#";
    for( int i=0; i< S.length(); i++){
        if(S[i] == "#")
            //do somethng
    }
    return 0;
}

On googling this error i found a workaround to this by using '&' as in if( &S[i] == "#") and it works fine. Can someone please enlighten me on why this works, what's happening here ?

xvzf
  • 137
  • 1
  • 10
  • `S[i]` is a character, so it should be compared with an other character, not a string: `if(S[i] == '#')` – m88 Jan 17 '20 at 12:45
  • 1
    dont confuse no compiler errors with "works fine". `if( &S[i] == "#")` is likely not doing what you think it does – 463035818_is_not_an_ai Jan 17 '20 at 12:46
  • @m88 Thanks. I get it now. – xvzf Jan 17 '20 at 12:49
  • Does this answer your question? [c++ compile error: ISO C++ forbids comparison between pointer and integer](https://stackoverflow.com/questions/2263681/c-compile-error-iso-c-forbids-comparison-between-pointer-and-integer) – Chris Feb 21 '21 at 22:49

2 Answers2

4

You're iterating over characters, but you compare the character (char) against (const char *).

You should be comparing it to a character '#'.

#include <iostream>
using namespace std;

int main() {
    string S = "a#b#";
    for( int i=0; i< S.length(); i++){
        if(S[i] == '#') // here <--
            //do somethng
    }
    return 0;
}

You can simplify this to a range based for loop:

#include <iostream>
using namespace std;

int main() {
    string S = "a#b#";
    for(char character : S){
        if(character == '#')
            //do somethng
    }
    return 0;
}
deW1
  • 5,562
  • 10
  • 38
  • 54
0

&S[i] == "#" is not as same as s[i]=='#', since former one compares pointer address it evaluates to false.