Learn MISRA-C-CPP with Real Code Examples
Updated Nov 27, 2025
Code Sample Descriptions
1
MISRA C: Rule Example (Avoid Implicit Conversion)
/* Non-compliant: implicit conversion */
char c = 300;
/* Compliant: explicit cast with proper range check */
int value = 300;
char c;
if ((value >= CHAR_MIN) && (value <= CHAR_MAX))
{
c = (char)value;
}
Example showing how to follow MISRA C by avoiding implicit type conversions.
2
MISRA C++: Rule Example (No Dynamic Memory in Safety-Critical Code)
// Non-compliant: dynamic allocation
int* data = new int[10];
// Compliant: use static or stack allocation
int data[10];
MISRA C++ discourages dynamic allocation in safety-critical systems. Example shows a compliant static allocation approach.
3
MISRA C: Rule Example (Use of const)
/* Non-compliant */
int maxValue = 100;
/* Compliant */
const int maxValue = 100;
Ensures immutability of variables where possible.
4
MISRA C: Rule Example (No goto)
/* Non-compliant */
goto error;
/* Compliant */
if (error_condition) {
/* handle error */
}
Avoid using goto statements to maintain structured flow.
5
MISRA C: Rule Example (Initialize Variables)
/* Non-compliant */
int counter;
/* Compliant */
int counter = 0;
Always initialize variables to avoid undefined behavior.
6
MISRA C++: Rule Example (Avoid Multiple Inheritance)
// Non-compliant
class Derived : public Base1, public Base2 {};
// Compliant
class Derived : public Base1 {};
Avoid multiple inheritance to reduce complexity.
7
MISRA C: Rule Example (Avoid Magic Numbers)
/* Non-compliant */
int delay = 1000;
/* Compliant */
#define DELAY_MS 1000
int delay = DELAY_MS;
Use named constants instead of magic numbers.
8
MISRA C: Rule Example (Single Point of Exit)
/* Non-compliant */
int compute(int x) {
if (x < 0) return -1;
return x * 2;
}
/* Compliant */
int compute(int x) {
int result;
if (x < 0) {
result = -1;
} else {
result = x * 2;
}
return result;
}
Maintain a single return point in functions.
9
MISRA C++: Rule Example (No Exception Handling in Safety-Critical)
// Non-compliant
try {
/* code */
} catch (...) {}
// Compliant
if (error_condition) {
/* handle error */
}
Avoid exceptions in safety-critical code.
10
MISRA C: Rule Example (Boolean Expressions)
/* Non-compliant */
int flag = 1;
if (flag) {
/* do something */
}
/* Compliant */
bool flag = true;
if (flag) {
/* do something */
}
Use explicit boolean expressions rather than integers.