Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This compliant solution mimics the behavior of static_assert in a portable manner.

Code Block
bgColor#ccccff
#define JOIN(x, y) JOIN_AGAIN(x, y)
#define JOIN_AGAIN(x, y) x ## y

#define static_assert(e) \
typedef char JOIN(assertion_failed_at_line_, __LINE__) [(e) ? 1 : -1]

struct timer {
  uint8_t MODE;
  uint32_t DATA;
  uint32_t COUNT;
};

static_assert(offsetof(struct timer, DATA) == 4);

...

,

...

 "Member DATA is not 4-byte aligned");

Static assertions allow incorrect assumptions to be diagnosed at compile time, instead of resulting in a silent malfunction or runtime error. Because the assertion is performed at compile time, no runtime cost in space or time is incurred. An assertion can be used at file or block scope, and failure results in a meaningful and informative diagnostic error message.

...