0
char str1[]="abc";
char str2[]="abc";

if (str1==str2)
    printf("Yes")
else
    printf("No");

I am refreshing my C. Wouldn't the above code return "Yes"? I think it would because str1 and str2 are pointing to the first elements of the array, which are the same (the letter a). Please advise if I am missing something.

isedev
  • 18,848
  • 3
  • 60
  • 59
To Pa
  • 11

2 Answers2

0

The variable name of a char array is equivalent to a pointer to the address of the first element of the array. Therefore, what you are comparing are pointers. They are not equivalent because the address of the two variables in memory are not equivalent.

trieck
  • 51
  • 3
0

Technically, you are comparing string addresses. So without optimisations, the expected answer is "No" (two different strings, hence two addresses).

However, most modern compilers perform string interning (merging identical constants strings), in which case the answer would be "Yes". Note this only happens for string literals.

For instance, GCC 4.9.2 does this by default:

#include <stdio.h>
int
main()
{
    char *ptr1 = "abc";
    char *ptr2 = "abc";
    printf("%p\n%p\n",ptr1,ptr2);
    if (ptr1 == ptr2) printf("yes\n");
}

gcc -o /tmp/file /tmp/file.c

/tmp/file
0x400660
0x400660
yes

Interestingly, behaviour is different (i.e. no interning) when declaring the variables char ptr1[] and char ptr2[]. This is because, in that case, the compiler actually places the strings on the stack (see here).

As stated in comments, the proper way to compare strings is strcmp and related functions.

Community
  • 1
  • 1
isedev
  • 18,848
  • 3
  • 60
  • 59