I would like a static assertion to be sure that a given expression is a string literal. I tried this:
#define SAME_TYPES(x, y) __builtin_types_compatible_p(typeof(x), typeof(y))
#define IS_ARRAY(x) !SAME_TYPES((x), &(x)[0])
#define IS_COMPILE_TIME_STR(x) IS_ARRAY(x) && #x[0] == '"'
#define ASSERT_COMPILE_TIME_STR(x) static_assert(IS_COMPILE_TIME_STR(x), "Only static allocated compile time strings are allowed, but got this: " #x)
/*
* ASSERT_COMPILE_TIME_STR("hey"); <-- this is fine
* ASSERT_COMPILE_TIME_STR(1234); <-- this should fail
*/
Unfortunately, ASSERT_COMPILE_TIME_STR does not work, because #x[0] == '"' does not seem to be a compile-time-constant.
Is there some other way to achieve this? It just has to compile with gcc, so any kind of extensions are fine:)
Thanks a lot
x[0]because not every type has a subscript operator. C is the wrong language for this kind of stuff.#x[0]is actually always well-defined (even at compile-time).&(x)[0], that one is applied straight to1234which is why your code fails to compile.x[0]only tests whetherxhas a subscript operator is okay because it will not be the only test. From memory, I think there is another question on Stack Overflow about detecting arrays. However, testing for a string literal is harder.static_assertwith a meaningful error message. It is more important to answer in the spirit of the question than to seek a perceived goal at all cost.