You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.
You should not use == (equality operator) to compare these strings because they compare the reference of the string, i.e. whether they are the same object or not. On the other hand, equals() method compares whether the value of the strings is equal, and not the object itself.
C strcmp() The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.
String Comparison With Objects Class The method returns true if two Strings are equal by first comparing them using their address i.e “==”. Consequently, if both arguments are null, it returns true and if exactly one argument is null, it returns false.
I have this code:
char *name = "George"
if(name == "George")
printf("It's George")
I thought that c strings could not be compared with ==
sign and I have to use strcmp
. For unknown reason when I compile with gcc (version 4.7.3) this code works. 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. So why this comparing method works ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With