C Strings Comparison with Equal Sign

I thought that c strings could not be compared with == sign and I have to use strcmp

Right.

I though that this was wrong because it is like comparing pointers so I searched in google and many people say that it’s wrong and comparing with == can’t be done

That’s right too.

So why this comparing method works ?

It doesn’t “work”. It only appears to be working.

The reason why this happens is probably a compiler optimization: the two string literals are identical, so the compiler really generates only one instance of them, and uses that very same pointer/array whenever the string literal is referenced.

Leave a Comment