0

I'm trying to implement my own macro assertion for learning purposes. The problem is I don't manage evaluate an expression at compile time (a compile-time evaluable expression of course) and to write a message at compile time in stdout/stderr. How does <assert.h> manage to do that? What I tried so far is a structure like:

#define MY_ASSERT(_EXPR) (\
#IF (_EXPR)
// don't know how to tell preprocess to write a message
#ENDIF \
)

but it is clearly wrong syntactically and maybe conceptually.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
  • you can use `#error` for that – Jean-François Fabre Jul 11 '22 at 14:38
  • `#IF` and `#ENDIF` meaningless (erroneous) in C (with lower-case spelling, they might be meaningful, but not in the body of a macro). Static assertions (`_Static_assert` aka `static_assert`) are evaluated at compile time; ordinary assertions are evaluated at runtime. For ordinary (dynamic?) assertions, you need the macro to expand to an expression. You'll need to use the stringize operator `#` to get the text of the expression into the message. You'll probably use a function to do the printing, rather than calling `fprintf()` or anything similar directly in the macro. – Jonathan Leffler Jul 11 '22 at 14:41

0 Answers0