-1

why can't we compare two strings in c program directly.For example i have tried the following example

char *str="int";
if(str=="int")
printf("yes");
else
printf("no");

For the above I got output as "no" I have tried the above code by using the same logic as if for integers ie

int i=10;
if(i==10)
printf("same");

But when I have modified the above code like the following

if((strcmp(str,"int"))==0)
printf("yes");

I got the output as "yes" What is the problem in the first stated code?

  • a char pointer is not an int – Cyclonecode Mar 10 '15 at 01:49
  • An advice: before asking here try to find the answer yourself. The question is extremely basic (hence the downvotes). Asking it shows that you have invested very little effort. That is embarassing to you and annoying to us. I was nice and answered anyway -- assuming that you come from, say, C#, it can be a bit puzzling. But be aware that C# made special arrangements for strings, or they would not be "equal" according to `operator==` either! Not any more than any average reference type of your choice. – Peter - Reinstate Monica Mar 10 '15 at 01:55
  • In a way the answer should be "you can"; however, the result will not be what you would expect because your comparing pointers, not the characters they point to. =) – Segmented Mar 10 '15 at 01:58

1 Answers1

4

A "string" in C is just an array of chars. Comparing two arrays with == just compares their addresses, which are different for different arrays. (Literals may or may not be the same, actually, depending on the implementation.)

Peter - Reinstate Monica
  • 15,048
  • 4
  • 37
  • 62