Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a static_assert replacement which satisfies the C99 standard?

I have been trying to implement a method similar to static_assert which is defined in the C++11 standard. The main problem is how does the C++ compiler write the text message being passed to static_assert as a const char*? I can get the compiler to write a message like A_is_not_POD. This is what I have:

#define MY_STATIC_ASSERT(condition, name)         \
   typedef char name[(condition) ? 1 : -1]; 

But it would be quite nice to get the compiler to write something like "Error: A is not POD." Any suggestions?

like image 439
Shubham Avatar asked Dec 06 '13 14:12

Shubham


People also ask

What is the difference between assert and static_assert?

A static_assert is an assertion that is checked at compile-time rather than at runtime, with a failing static_assert causing a compile error. Unlike assert, which is declared in the <cassert> header, static_assert is a keyword, so no header needs to be included to use it.

What is static_assert?

What is static assertion? Static assertions are a way to check if a condition is true when the code is compiled. If it isn't, the compiler is required to issue an error message and stop the compiling process. The condition that needs to be checked is a constant expression. Performs compile-time assertion checking.

Is static assert compile-time?

Of course, the expression in static assertion has to be a compile-time constant. It can't be a run-time value. For run-time values you have no other choice but use the ordinary assert .


1 Answers

Not sure i understand question, but C11 have _Static_assert(condition, errmessage). In C99 this functionality was missing but, depending on compiler, it could be possible to emulate. E.g. for gcc (unfortulately clang doesn't support attribute(error))

#define MY_STATIC_ASSERT(cnd, descr) ({ \
    extern int __attribute__ ((error("static assert failed: (" #cnd ") (" #descr ")"))) \
               compile_time_check(void); \
    ((cnd) ? 0 : compile_time_check()), 0; \
})
like image 71
keltar Avatar answered Oct 10 '22 17:10

keltar