-4

I am comparing string using if condition but the second if condition is failing. What will be the reason of fail and what happens in compiler level in these comparing cases?

char *c = "test";
char a[] = "test";

if(c=="test")
{
    printf("Hai\n");
    if(a=="test")
    printf("Bye\n");
}
PSatishKR
  • 40
  • 7

1 Answers1

2

In the first comparison you should get a warning:

warning: result of comparison against a string literal is unspecified

However it returns true because you are comparing two pointers to string literal, witch is always, as far as I can tell, the same. Take the following code:

#include <stdio.h>
#include <string.h>

int main(void) {
  char *c = "test";
  char a[] = "test";

  printf("%p\n%p\n%p", c, a, "test");
}

The results will be:

0x4005f4

0x7ffedb3caaf3

0x4005f4

As you can see the pointers are indeed the same.

That said, == is not used in C to compare strings, you should use strcmp().

#include <stdio.h>
#include <string.h>

int main(void) {
  char *c = "test";
  char a[] = "test";

  if(!strcmp(c, "test"))
  {
    printf("Hai\n");
    if(!strcmp(a, "test"))
      printf("Bye\n");
  }
}

anastaciu
  • 23,467
  • 7
  • 28
  • 53