C ++ compares two string literals

When comparing a string literal with another string literal with an operator ==(or !=), is the result correct?

For example, are the following conditions guaranteed?

assert("a" == "a");
assert("a" != "b");

Please do not say things like "use std :: string". I just want to know this particular case.

+5
source share
2 answers
"a" == "a"

This expression can give trueor false; there are no guarantees. Two string literals "a"can occupy the same storage, or they can exist in two different memory locations.

, ++: " ( , ) - , " (++ 11 §2.14.5/12). , .

"a" != "b"

false, , : "a"[0] != "b"[0].


, .

, (<, >, <= >=) , (== !=), . , .

"a" , "a" < "a" false, ('a') .

, "a" , "a" < "a" undefined, , , .

"a" "b" , "a" < "b" undefined. .

, - , , std::less -, - . std::greater, std::greater_equal std::less_equal. , , , - , .

+15

, ++ . , , - , , , . "a" "b" , "a" != "B" . . "a" == "a", GCC -fmerge- ( -O1) , - -fmerge ( ).

, assert(!strcmp("a", "a")). - strcmp constexpr :

constexpr bool static_strequal_helper(const char * a, const char * b, unsigned len) {
   return (len == 0) ? true : ((*a == *b) ? static_strequal_helper(a + 1, b + 1, len - 1) : false);
}

template <unsigned N1, unsigned N2>
constexpr bool static_strequal(const char (&str1)[N1], const char (&str2)[N2]) {
   return (N1 == N2) ? static_strequal_helper(&(str1[0]), &(str2[0]), N1) : false;
}

static_assert(static_strequal("asdf", "asdf"), "no error - strings are equal");
static_assert(static_strequal("asdf", "jkl;"), "strings are not equal");
assert(!strcmp("asdf", "jkl;")); //no compile error - runtime error
//cannot use strcmp in static assert as strcmp is not constexpr...

g++ -std = ++ 0x ( -std = ++ 11 gcc >= 4.7) ...

error: static assertion failed: "strings are not equal"
+1

All Articles