0

Why can't I use the == operator to compare two string variables in C? Example:

char name1[] = "John";
char name2[] = "John";
if (name1==name2)
printf("Same!");
Crossunit
  • 9
  • 3
  • 4
    Because that's comparing addresses, not contents. You have to use `strcmp()` to compare strings. – Barmar Sep 29 '22 at 14:48
  • Because the `string` type doesn't exist in C. A string of character is a derived type made using an array of `char` conventionally ended with a null. To compare two arrays you must use functions comparing element by element. A specialized function exist in C to check strings, `strcmp()`, that compare the two characters array element by element and stops when a difference is encountered or a null character is found. It returns -1, 0 or 1 respectively if string1 is less than, equal or greater then string2. – Frankie_C Sep 29 '22 at 14:56
  • This should have been explained in whatever textbook or tutorial you used to learn C. – Barmar Sep 29 '22 at 14:59
  • Would you want the characters of `name1` to change if somebody modified characters of your `name2`? Because that's what would happen if they were equal. – Dmytro Sep 29 '22 at 15:02
  • 1
    Under most circumstances, array expressions "decay" to pointers to their first element - what you've written is equivalent to `if ( &name1[0] == &name2[0] )`, which will never be true. There *is* a reason for that behavior, but it's too long to fit in a comment. Similarly, you can't use `=` to assign an entire array (such as `name1 = "foo"`). You have to use the `strcmp` library function to compare strings (`if ( strcmp(name1, name2) == 0 )`), and you have to use functions like `strcpy` to assign strings (`strcpy( name1, "foo" );`). – John Bode Sep 29 '22 at 15:08
  • @Frankie_C `strcmp()` returns any positive or negative non-zero value if strings are not equal. – dimich Sep 30 '22 at 09:32
  • @dimich Thanks for the clarification. I simplified the the concept, but forget to mention my older answer here: https://stackoverflow.com/questions/36518931/what-does-strcmp-return-if-two-similar-strings-are-of-different-lengths/36519262#36519262, which is much more detailed. – Frankie_C Sep 30 '22 at 21:44

0 Answers0