c++assertstatic-assert

static_assert vs C_ASSERT - which one to use?


I have a general C++ / Windows question for coding standards regarding compile-time assertions.

static_assert is C++11 and language/compiler supported;
C_ASSERT is a define from winnt.h

So, if I have C++ Windows code - which one should I use? Why? What are the advantages of one over the other?

I tested both - there is a difference in the error message.


Solution

  • Based on the documentation, you should use static_assert over C_ASSERT.

    1. If you are limited to C++11, it requires you to provide a message explaining why the compilation failed.
    2. If you don't want to display a message, moving to C++17 gives you a similar definition to C_ASSERT.
    3. It is preferred in C++ to avoid macro's whenever possible.
    4. It is more likely to be compatible with all the different compile time features that C++ has compared to the macro.
    5. It is platform-independent and performs the same task