1
#include<stdio.h>

int main()
{
    char str1[] = "ComputerProgram";
    char str2[] = "ComputerProgram";
    (str1==str2)? (printf("Equal")):(printf("unequal"));
    return 0;
}

The answer according to me should be equal but it comes out to be unequal. However if I use strcmp(str1,str2) == 0 answer comes out to be equal. How is it working in == case.? Also, I tried to print the ASCII values of srt1 and str2, they came out to be different. So I think that might be the reason. Now the problem is how does == work for strings?

Shubham
  • 2,847
  • 4
  • 24
  • 37

2 Answers2

3

Your arrays str1 and str2 will decay to pointers to their first elements when you compare them. That is, you compare two pointers that will never be equal.

In short, your comparison str1 == str2 is equal to &str1[0] == &str2[0].

What strcmp does differently is that is compares each character in the first string against each corresponding character in the other string, in a loop.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
  • Thanks .. Just checked the adresses and yes they are different.. thanks alot – Blazingminds Ggn May 04 '18 at 06:41
  • 1
    Instead of repeatedly answering common FAQs, you could open up the [C tag wiki](https://stackoverflow.com/tags/c/info), scroll down to FAQ, find the section called strings, find the relevant canonical duplicate and then close vote. – Lundin May 04 '18 at 06:54
0

str1==str2 is comparing the addresses of the strings, not the strings themselves.strcmp will go to these addresses and compare all characters.

Martin Chekurov
  • 733
  • 4
  • 15