cstring-literalsstatic-assert

How to check a string literal in static_assert?


I want to check, that a string literal doesn't have some specific value.

#include <assert.h>
static_assert("aaa"[0] != 'a');

However, this results in this error:

error: expression in static assertion is not constant

How can this be achieved? Why doesn't it work, given that all data is known at compile time?


Solution

  • static_assert requires an integer constant expression (not to be confused with const) as parameter. So the issue is what C regards as a an integer constant expression. It's rather picky with this (C23 6.6):

    An integer constant expression shall have integer type and shall only have operands that are integer constants, named and compound literal constants of integer type, character constants, sizeof expressions whose results are integer constants, alignof expressions, and floating, named, or compound literal constants of arithmetic type that are the immediate operands of casts.

    String literals isn't among any of these, hence the error.

    However, the standard allows implementation-defined (meaning compiler-specific) forms on constant expressions, why for example some compilers like clang might accept the code. But code relying on that is not portable.

    Similarly, C++ is more lenient to various forms of constant expressions than C, so if you happen to compile the code as C++ by accident, that would work too.