2

Learning c++ and reading through a project, I found this.

#define EMPTY_MACRO do {} while (0)

...

#if ASSERTS_ENABLED
#define ASSERTCORE(expr) assert(expr)
#else
#define ASSERTCORE(expr) EMPTY_MACRO
#endif

What is the purpose of EMPTY_MACRO? Is it unnecessary or is there a reason for it?

Nonne
  • 25
  • 3
  • 6
    One consequence would be that if you did `#define EMPTY_MACRO` to make it just nothing, then you could place `ASSERTCORE` in places where it's not actually syntactically valid to place an assertion and you wouldn't realize anything was wrong until you turned `ASSERTS_ENABLED` on. – Nathan Pierson Jun 27 '22 at 16:31
  • 2
    The `do{}while(0)` will play nice with the trailing semicolon from `ASSERTCORE(true);` – Eljay Jun 27 '22 at 16:34
  • 2
    For example of the kind of thing I mean: [See here](https://godbolt.org/z/odMrYnxbo). If `EMPTY_MACRO` is an entire little trivial do-while loop, then it refuses to compile even if I haven't set `ASSERTS_ENABLED`. But if I just make `EMPTY_MACRO` empty, then it happily lets me place the macro where it doesn't belong. – Nathan Pierson Jun 27 '22 at 16:37
  • by the way, none of this is C++, inherently. On the contrary, this is a very C, and a very un-C++-like way of solving the problem of compile-time disabling assertions. – Marcus Müller Jun 27 '22 at 17:12
  • Therefore: If you're learning C++, the code you're looking through is *probably* not a good example! – Marcus Müller Jun 27 '22 at 17:21

1 Answers1

3

It's there so

ASSERTCORE(expr);

behaves the same with or without ASSERTS_ENABLED. A plain #define ASSERTCORE(expr) would leave behind a lone ; and that would behave differently in some cases.

Goswin von Brederlow
  • 11,875
  • 2
  • 24
  • 42