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.


Just to provide a reference to @H2CO3's answer:

C11 6.4.5 String literals

It is unspecified whether these arrays are distinct provided their elements have the appropriate values. If the program attempts to modify such an array, the behavior is undefined.

This means that in your example, name(a string literal "George") and "George" may and may not share the same location, it's up to the implementation. So don't count on this, it may results differently in other machines.


The comparison you have done compares the location of the two strings, rather than their content. It just so happens that your compiler decided to only create one string literal containing the characters "George". This means that the location of the string stored in name and the location of the second "George" are the same, so the comparison returns non-zero.

The compiler is not required to do this, however - it could just as easily create two different string literals, with different locations but the same content, and the comparison would then return zero.