Search code examples
c++string-comparison

Why does operator== work for statically initialized char*?


When creating a char array like:

char c_array1[] = { "str1" };
char c_array2[] = { "str1" };
char* cp_array1 = c_array1;
char* cp_array2 = c_array2;
if(cp_array1 == cp_array2) { // char* cannot be compared with char*

The comparison does fail. But with statically initialized char*:

char* cp_array1 = "str1";
char* cp_array2 = "str1";
if(cp_array1 == cp_array2) { // char* can be compared with char*

It works. Why does the operator== behave differently for the same type of parameters in this case?


Solution

  • "But with statically initialized char* It works" - It may work - if the compiler optimized your code to store only one str1 (which it is allowed to do).

    You are comparing pointers - not the strings they point at.

    If you want to compare the strings, use std::strcmp:

    if(std::strcmp(cp_array1, cp_array2)) {
        // not equal
    } else {
        // equal
    }
    

    The strings are const though, so it should be const char* cp_array1 = "str1"; and const char* cp_array2 = "str1";