Ground Embedded KO Subscribe

Notes / Firmware Design & Quality

Coding rules: what MISRA C prevents

What MISRA C, used in automotive and industrial firmware, forbids, and why.

GROUND EMBEDDED · NOTEFirmware Design & Quality 03Coding rules 1volatile uint32_t *ODR 2 = (uint32_t*)0x40020014; 3*ODR |= (1u << 5); 4while (1) { 5 if (flag) toggle(); 6}

MISRA C is a set of rules that restricts the dangerous features of C so that people write predictable, verifiable code. In the automotive industry it is effectively the standard.

Representative rules and reasons

Rule (in outline) Reason
No dynamic memory allocation Fragmentation, failure, unpredictable timing
No recursion Stack usage cannot be predicted
Restricted goto Flow is hard to follow
A default in every switch Handles unexpected values
Restricted implicit conversions Sign and size conversion bugs
Function return values must not be ignored So errors are not let through
Inline functions over macros Side effects, type checking
No == comparison of floating point Rounding error

How it is used in practice

Write codeStatic analysis toolflags violationsFix, or record the reasonReview
Rules are checked by tools, not by people.
  • Checked automatically with static analysis tools (PC-lint, Polyspace, Helix QAC, the MISRA add-on for cppcheck).
  • Where a rule really has to be broken, a deviation is documented and approved.
  • Understand the purpose of the rules and they become good habits even in projects that do not use MISRA.

Seen alongside it

CERT C (security-focused), and the company's own coding style (naming, indentation). Leave formatting to an automatic formatter (clang-format) and concentrate on logic in review.

FREE PDFGet the 3 free ebooksIf you want to keep reading this topic as one book: BLDC motor control, serial communication and sensors at book length. PDFs are in Korean.Get them free →