C equality of constant lines

Is the following comparison guaranteed true ?

"hello world"=="hello world"; 

In addition, false is always guaranteed:

 char a[] = "hello world"; a == "hello world"; 
+1
source share
4 answers

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

for

 "hello world"=="hello world"; 

the comparison is allowed to be true or false . Standard C says in 6.4.5 "String literals":

It is not known whether these arrays are different if their elements have corresponding values.

Thus, the standard allows you to store literals 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 from the address of the string literal.

+8
source

In C, you need to use a function that compares strings for you. By doing this, you simply say if there are two lines in one place in memory. So

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

creature

 a == b; 

will give you a true value, since both a and b point to the same place or line in memory.

If you want to compare two strings, you will need to use strcmp() , which returns 0 if the strings are equal.

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

To use it, you need to enable the string.h library.

 #include <string.h> 
+1
source

Comparing the contents of a string is not allowed using the == 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"; 
0
source
Operator

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

0
source

Source: https://habr.com/ru/post/978642/


All Articles