How can you compare two character strings statically at compile time How can you compare two character strings statically at compile time xcode xcode

How can you compare two character strings statically at compile time


You can do this with C++11 by using a constexpr function:

constexpr bool strings_equal(char const * a, char const * b) {    return *a == *b && (*a == '\0' || strings_equal(a + 1, b + 1));}

(See a demo)

It's not possible to do this prior to C++11, with the caveat that many compilers will compile equal string literals to be a pointer to the same location. On these compilers it's sufficient to compare the strings directly since they will both be evaluated as equal pointers.


Starting with C++17 std::string_view is available. It supports constexpr comparisson:

#include <string_view>constexpr bool strings_equal(char const * a, char const * b) {    return std::string_view(a)==b;}int main() {    static_assert(strings_equal("abc", "abc" ), "strings are equal");    static_assert(!strings_equal("abc", "abcd"), "strings are not equal");    return 0;}

Demo


You can use constexpr functions. Here's the C++14 way:

constexpr bool equal( char const* lhs, char const* rhs ){    while (*lhs || *rhs)        if (*lhs++ != *rhs++)            return false;    return true;}

Demo.