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";
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";
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.
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>
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";
==
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.