Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C Strings Comparison with Equal Sign

Tags:

People also ask

Can you compare strings with == in C?

You can't compare strings in C with ==, because the C compiler does not really have a clue about strings beyond a string-literal.

Can we use == for string comparison?

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.

How do you check if a string is equal to another string in C?

C strcmp() The strcmp() compares two strings character by character. If the strings are equal, the function returns 0.

What happens when you compare strings with ==?

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 ?