简体   繁体   English

为什么C ==对于相等的字符串返回true?

[英]Why does C == return true for equal strings?

if( "string1" == "string2" )    

Why does this work in C? 为什么这在C中起作用? It returns true when strings are equal? 当字符串相等时返回true? How? 怎么样? For example, it doesn't work in Java because the pointers are compared. 例如,它在Java中不起作用,因为会比较指针。

The C99 Rationale says on string literals (emphasis mine): C99基本原理对字符串文字(强调我的意思)说:

"This specification allows implementations to share copies of strings with identical text , to place string literals in read-only memory, and to perform certain optimizations". “此规范允许实现共享具有相同文本的字符串副本 ,将字符串文字放入只读存储器中,并执行某些优化”。

It is allowed but non-required so the result could be different with a different implementation or with the same implementation if the program is slightly different. 它是允许的,但不是必需的,因此如果程序稍有不同,则对于不同的实现或相同的实现,结果可能会有所不同。

I think comparing string using 'if( "string1" == "string2" )' is comparing pointers to string literals in C. You could refer to the following post:- C String -- Using Equality Operator == for comparing two strings for equality 我认为使用'if(“ string1” ==“ string2”)'比较字符串是比较指向C中字符串文字的指针。您可以参考以下文章: -C String-使用Equality Operator ==比较两个字符串平等

int main() {

    if( "string1" == "string1" ) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal\n");
    }

    if( "string1" == "string2" ) {
        printf("Strings are equal\n");
    } else {
        printf("Strings are not equal\n");
    }

    char* s1 = "string1";
    char* s2 = "string2";

    printf("%s = %p %s = %p\n", s1, s1, s2, s2);
    return(0);
}

There are two if blocks in the above main function. 上述主要功能中有两个if块。 One of them if comparing "string1" with itself which will result in TRUE. 其中之一,如果将“ string1”与其自身进行比较,则结果为TRUE。 The second is comparing "string1" and "string2" which will result in FALSE. 第二个是比较“ string1”和“ string2”,结果为FALSE。 If you assign pointers to the string literals and print their addresses you will be able to see why in the first if block you get TRUE value and in the second if block you get the FALSE value. 如果将指针分配给字符串文字并打印其地址,您将能够理解为什么在第一个if块中获得TRUE值,而在第二个if块中获得FALSE值的原因。 Following is the output:- 以下是输出:-

GAGUPTA2-M-40UT:Desktop gagupta2$ ./a.out 
Strings are equal
Strings are not equal
string1 = 0x105f6ef50 string2 = 0x105f6ef82

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM