1

Is the following comparison guaranteed to be true?

"hello world"=="hello world";

Also, is the following always guaranteed to be false?

char a[] = "hello world";
a == "hello world";
  • 2
    strings, irregardless of their physical location must be compared using one of the string functions, like strcmp( "hello world", "hello world" ); I.E. the comparison operator '==' will only be comparing the address(s) of the arrays, which may or may not be identical. – user3629249 Nov 23 '14 at 10:54

4 Answers4

8

To be clear - in both cases you are comparing pointers, not the actual string contents.

for

"hello world"=="hello world";

it is permitted that the comparison be true or false. The C standard says in 6.4.5 "String literals":

It is unspecified whether these arrays are distinct provided their elements have the appropriate values.

So the standard allows the storage for the literals to be the same or different.

For

char a[] = "hello world";
a == "hello world";

the comparison will always be false since the address of the array a must be different than the address of the string literal.

Michael Burr
  • 333,147
  • 50
  • 533
  • 760
1

In C you have to use a function that compare the strings for you. Doing it straigh away will only tell you if two strings are in the same place on the memory. so

char a[] = "hello world";
char b[] = a;

the making

a == b;

will give you true because both a and b have point to the same place, or string, in the memory.

If you want to compare two strings you'll have to use strcmp() that returns 0 if the strings are equal.

if( strcmp(a, b) == 0 )
    printf("True\n");
else
    printf("False\n");

To use it you'll need to include the library string.h.

#include <string.h>
Victor
  • 319
  • 2
  • 10
0

Comparing string contents is not allowed through == operator in C. You should use

strcmp(str1,str2);

In this case you are comparing pointers. So

"hello world" == "hello world";

may or may not be TRUE.

But the second case is always FALSE.

char a[] = "hello world";
a == "hello world";
Gopi
  • 19,784
  • 4
  • 24
  • 36
  • 1
    That's not the question. To be precise, it's legal to use `==` to compare strings, but the result is comparing pointers, not the string content. – Yu Hao Nov 23 '14 at 06:51
  • What YuHao said is right. In addition,`stcmp(str1,str2)` is wrong too!(typo) – Spikatrix Nov 23 '14 at 07:03
  • @YuHao Agree == can be used to compare pointers as in this case. But it doesn't make sense to compare pointers as done here. So the intention I guess here is to compare string contents so I suggested ti use strcmp() – Gopi Nov 23 '14 at 07:11
0

== operator in C can be used to compare primitive data types. Since String are not primitive in C,you can't use the == to compare them. The best option is to use the strcmp() function by including string.h library.

Fawzan
  • 4,738
  • 8
  • 41
  • 85