0

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.

6
  • 3
    In general, portable code is preferable to implementation-specific code. Commented Aug 6, 2024 at 21:35
  • 1
    Especially if using non-portable code doesn’t gain you anything. Commented Aug 6, 2024 at 21:45
  • 2
    Keep in mind that the Win32 API has to support both C and C++, new and old, so it uses a lot of abstractions that allow it to do different things under different configurations to maintain a consistent interface. If you are targeting C++ only, especially C++11 or later, then there is simply no reason to use C_ASSERT over static_assert. static_assert is standard C++. C_ASSERT is a Microsoft-specific invention. Commented Aug 6, 2024 at 21:46
  • Regarding portability, you also have to ask if the code needs to be portable to older toolchains. I.e. if it is more likely to need to be built on an older visual studio that doesn't support it in the language than needing to be built on a non-Windows platform. Commented Aug 6, 2024 at 21:46
  • @RemyLebeau And even in C since C11, it also has static_assert (when <assert.h> is included). Commented Aug 6, 2024 at 21:56

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Very comprehensive answer! Thank you!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.