Comparing Equal Sign Strings

I have this code:

char *name = "George" if(name == "George") printf("It George") 

I thought c lines could not match the == sign, and I should use strcmp . For some unknown reason, when compiling with gcc (version 4.7.3), this code works. I, although it was wrong, because it was like comparing pointers, so I searched on google and many people say that it is wrong and comparing with == impossible. So why does this comparison method work?

+6
c string c-strings
Jul 22 '13 at 7:13
source share
5 answers

I thought the c lines could not match the == sign and I need to use strcmp

Right

I, although it was wrong, because it looks like a comparison of pointers, so I searched on google and many people say that it is wrong and comparison with == cannot be done

It is too.

So why does this comparison method work?

He does not work. It seems to work.

The reason this happens is probably a compiler optimization: the two string literals are identical, so the compiler really only generates one instance from them and uses the same pointer / array whenever it refers to a string literal.

+27
Jul 22 '13 at 7:16
source share

Just to provide a link to @ H2CO3's answer:

C11 6.4.5 String literals

It is not known whether these arrays are different if their elements have corresponding values. If the program tries to change such an array, the behavior is undefined.

This means that in your example, name (the string literal "George") and "George" can and cannot share the same location, right up to the implementation. So do not count on it, it can be otherwise differently in other machines.

+8
Jul 22 '13 at 7:33
source share

The comparison performed compares the location of two lines, not their contents. It so happened that your compiler decided to create only one string literal containing the characters "George" . This means that the location of the string stored in name and the location of the second "George" match, so the comparison returns a non-zero value.

The compiler is not required to do this, however - it can just as easily create two different string literals with different locations, but with the same content, and then the comparison will return zero.

+4
Jul 22 '13 at 7:19
source share

This will fail because you are comparing two different pointers of two separate lines. If this code still works, then this is the result of a great GCC optimization that only stores one copy for size optimization.

Use strcmp() . Link

+1
Jul 22 '13 at 7:16
source share

If you are comparing two stings, you are comparing the base addresses of these strings, and not the actual characters in these strings. to compare strings, use the strcmp() and strcasecmp() library functions or write such a program. below is not the full logic needed to compare strings.

 void mystrcmp(const char *source,char *dest) { for(i=0;source[i] != '\0';i++) dest[i] = source[i]; dest[i] = 0; } 
0
Jul 22 '13 at 7:57
source share



All Articles