Versions Compared

Key

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

...

This noncompliant code uses the assert() macro to assert a property concerning a memory-mapped structure that is essential for the code to behave correctly.

Code Block
bgColor#FFCCCC
langc
struct timer {
  uint8_t MODE;
  uint32_t DATA;
  uint32_t COUNT;
};

int func(void) {
  assert(offsetof(timer, DATA) == 4);
}

...

For assertions involving only constant expressions, some implementations allow the use of a preprocessor conditional statement, as in this example:

Code Block
bgColor#ccccff
langc
struct timer {
  uint8_t MODE;
  uint32_t DATA;
  uint32_t COUNT;
};

#if (offsetof(timer, DATA) != 4)
  #error "DATA must be at offset 4"
#endif

...

This portable compliant solution uses static_assert.

Code Block
bgColor#ccccff
langc
struct timer {
  uint8_t MODE;
  uint32_t DATA;
  uint32_t COUNT;
};

static_assert(offsetof(struct timer, DATA) == 4, "DATA must be at offset 4");

...