C Strings Comparison with Equal Sign

后端 未结 5 615
借酒劲吻你
借酒劲吻你 2020-11-29 12:45

I have this code:

char *name = \"George\"

if(name == \"George\")
   printf(\"It\'s George\")

I thought that c strings could not be compare

5条回答
  •  野性不改
    2020-11-29 13:10

    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.

提交回复
热议问题