Skip to main content
CodeSpeedTest
Languages
Start TypingJump into a test — pick any languageAdaptive TrainingUnlock chars as you master themPractice DrillsFocused sessions targeting weak spotsDaily ChallengesNew coding challenges every dayRace ModeCompete against others in real timeAI OpponentRace against an AI at your WPM levelTournamentsLive coding speed tournamentsArcade GamesZType, Overkill Survival, Glyphica & moreGamificationXP, coins, badges & quests
LeaderboardGlobal rankings for every languageCertificatesEarn verifiable Bronze / Silver / Gold certsActivityDaily streaks & historical analyticsProfileYour stats, badges & achievements
Browse Languages500+ languages with real code examplesBlogTips, guides & deep divesFree ToolsWPM calculator, typing speed report & moreFAQCommon questions answeredGetting StartedNew to CodeSpeedTest?AboutOur story & missionSupportGet help — Pro users get priorityContactGet in touch with the team
Pricing
  1. Home
  2. /
  3. Learn
  4. /
  5. Misra-c-cpp

Learn Misra-c-cpp - 10 Code Examples & CST Typing Practice Test

MISRA C and MISRA C++ are coding standards developed to facilitate safety, reliability, and maintainability in embedded systems, especially in automotive, aerospace, and critical industries.

View all 10 Misra-c-cpp code examples →
MISRA C: Rule Example (Avoid Implicit Conversion)MISRA C++: Rule Example (No Dynamic Memory in Safety-Critical Code)MISRA C: Rule Example (Use of const)MISRA C: Rule Example (No goto)MISRA C: Rule Example (Initialize Variables)MISRA C++: Rule Example (Avoid Multiple Inheritance)MISRA C: Rule Example (Avoid Magic Numbers)MISRA C: Rule Example (Single Point of Exit)MISRA C++: Rule Example (No Exception Handling in Safety-Critical)MISRA C: Rule Example (Boolean Expressions)

Learn MISRA-C-CPP with Real Code Examples

Updated Nov 27, 2025

Explain

MISRA provides a set of guidelines to avoid unsafe or undefined behavior in C/C++.

Focuses on safety, portability, readability, and maintainability of code.

Widely used in safety-critical embedded software development.

Rules cover language usage, coding practices, and static analysis requirements.

Adopted by automotive, aerospace, defense, and industrial sectors.

Core Features

MISRA C: 2004 / 2012 standard rules

MISRA C++: 2008 standard rules

Static analysis-friendly coding practices

Defined subsets to reduce undefined behaviors

Guidelines for portability across compilers and platforms

Basic Concepts Overview

Rule - a single guideline for safe coding

Directive - a high-level recommendation

Mandatory Rule - must always be followed

Advisory Rule - recommended best practice

Deviation - documented justification for violating a rule

Project Structure

Source files (.c/.cpp)

Header files (.h/.hpp)

Configuration files for analysis tools

Documentation of deviations

Test code for verification

Building Workflow

Write C/C++ code following MISRA guidelines

Run static analysis for rule violations

Document any justified deviations

Refactor code to address violations

Maintain compliance throughout project lifecycle

Difficulty Use Cases

Beginner: simple embedded C code adherence

Intermediate: C++ projects with OOP and templates

Advanced: multi-module ECU software

Expert: automotive or aerospace safety-critical projects

Architect: large-scale embedded system compliance

Comparisons

MISRA C vs CERT C: MISRA focuses on embedded safety, CERT on security

MISRA C++ vs C++ Core Guidelines: MISRA is strict for critical systems, Core Guidelines are general-purpose

MISRA C vs AUTOSAR C: MISRA is language rules, AUTOSAR provides architecture & middleware guidance

MISRA C vs JSF++: Both target safety, MISRA more industry-wide

MISRA vs ISO C/C++ standards: MISRA adds safety-focused constraints to standard C/C++

Versioning Timeline

1998 - MISRA C first edition released

2004 - MISRA C updated edition

2012 - MISRA C:2012 published

2008 - MISRA C++:2008 released

2016 - MISRA C:2012 Amendment 1

2020 - MISRA C:2012 Amendment 2

2022 - MISRA C++:2012 review discussions

Glossary

MISRA - Motor Industry Software Reliability Association

Rule - specific coding requirement

Directive - high-level recommendation

Deviation - approved rule violation

Static Analysis - automated code checking

Installation Setup

Obtain MISRA standard document (C, C++ versions)

Select compatible static analysis tool

Integrate analysis tool into build pipeline

Configure tool to enforce mandatory and advisory rules

Run code analysis and generate compliance reports

Environment Setup

C/C++ compiler toolchain installed

Static analysis tool configured

Project source code available

MISRA rules documented

Build and test environment set up

Config Files

Static analysis tool configuration files

MISRA rule selection files

Deviation documentation

Project-specific compliance reports

Build system integration files

Cli Commands

pc-lint / flexelint run

QA-C / QA-C++ analysis

clang-tidy --checks=misra

Polyspace MISRA check commands

Custom scripts for compliance reports

Internationalization

Not directly applicable

Comments and documentation may be multilingual

Variable naming conventions should be clear

Error messages may follow localization standards

Project-wide consistent naming

Accessibility

Code readable by all team members

Standard naming for variables and functions

Clear commenting for maintenance

Documentation for deviations

Consistent formatting for tools and reviews

Ui Styling

Not applicable

Style guidelines exist in code comments

Naming conventions for readability

Structured indentation for clarity

Consistent function and variable naming

State Management

Not applicable; code guidelines influence design state

Ensure deterministic program flow

Track deviation approvals

Maintain versioned compliance reports

Ensure safe memory and pointer usage

Data Management

Code review records

Static analysis output logs

Deviation documentation

Compliance reports per module

Archiving for certification audits

Architecture

Set of language rules and guidelines

Mandatory vs. advisory rules

Static code analysis tools enforce compliance

Documentation and rationale provided for each rule

Compliance reporting for audits

Rendering Model

Not applicable (code guidelines only)

Focus on language subset and safe constructs

Static analysis friendly

Code review checklists

Documentation for deviations

Architectural Patterns

Embedded software modularization

Strict type usage

Memory-safe programming

Predictable control flow

Deterministic behavior

Real World Architectures

Automotive ECU software

Aircraft flight control firmware

Industrial PLC controllers

Medical device embedded software

Railway signaling systems

Design Principles

Safety first in embedded software

Minimize undefined behavior

Increase code maintainability and readability

Enable portability across compilers

Support automated compliance checks

Scalability Guide

Apply rules module-wise

Integrate compliance checks into automated builds

Use analysis across multiple teams/projects

Track deviations centrally

Maintain compliance as codebase grows

Migration Guide

Legacy C code -> MISRA-compliant C

Identify violations using static analysis

Document justified deviations

Refactor code for mandatory rule compliance

Integrate compliance checks into CI/CD

Performance Notes

MISRA compliance may slightly increase development time

Static analysis tools may slow build process

Refactoring for compliance can improve runtime reliability

Reduces post-deployment defects

Enables safer optimization choices

Security Notes

Avoid unsafe functions prone to buffer overflows

Enforce type safety

Prevent undefined behavior that could lead to exploits

Document deviations to ensure safety review

Use MISRA alongside secure coding guidelines

Monitoring Analytics

Static analysis violation tracking

Deviation logs

Rule compliance percentage

Module-wise MISRA compliance

Trend analysis for rule violations over time

Code Quality

Follow all mandatory rules

Document deviations

Use static analysis tools regularly

Write maintainable and readable code

Ensure deterministic and safe behavior

Practical Examples

Checking rule compliance for pointer safety

Avoiding dynamic memory in safety-critical code

Ensuring strict type usage to prevent overflows

Implementing safe integer arithmetic

Enforcing code readability and maintainability standards

Troubleshooting

Check static analysis reports for rule violations

Identify deviations and justify if necessary

Refactor code for mandatory rule compliance

Ensure all headers and macros comply with rules

Rerun analysis after code changes

Testing Guide

Run static analysis during development

Verify mandatory rule compliance

Review advisory rule warnings

Document deviations in a deviation log

Repeat tests after code updates

Deployment Options

Include MISRA compliance checks in build

Continuous integration enforcement

Code review checklists with MISRA focus

Embedded runtime validation

Certification submissions for safety standards

Tools Ecosystem

PC-lint / FlexeLint

GCC MISRA plugin

CLang-Tidy with MISRA rules

QA-C / QA-C++

Polyspace MISRA compliance checker

Integrations

CI/CD pipelines for automated checking

Embedded development IDEs (IAR, Keil, Eclipse)

Version control systems (Git, SVN)

Build systems (Make, CMake)

Test frameworks for unit testing compliance

Productivity Tips

Integrate static analysis in CI/CD

Use code templates following MISRA

Modularize code to simplify compliance

Document deviations immediately

Perform peer reviews for MISRA adherence

Challenges

Strict adherence in legacy codebases

Balancing rule compliance with performance

Learning curve for new developers

Toolchain setup and integration

Documenting and justifying deviations

Learning Path

Learn C/C++ language basics

Understand undefined and implementation-defined behavior

Study MISRA C guidelines (2012 edition)

Study MISRA C++ guidelines (2008 edition)

Practice applying rules in embedded projects

Skill Improvement Plan

Week 1: Basic rules, naming conventions, type safety

Week 2: Pointers and memory management rules

Week 3: Control flow and function usage rules

Week 4: C++ OOP and template rules

Week 5: Static analysis and deviation documentation

Interview Questions

What is the purpose of MISRA C/C++?

What are mandatory vs advisory rules?

How do you justify a deviation from a MISRA rule?

How does MISRA improve embedded system safety?

What tools can enforce MISRA compliance?

Cheat Sheet

Rule 1.x -> Language subset

Rule 2.x -> Expressions & types

Rule 3.x -> Control statements

Rule 4.x -> Functions & pointers

Rule 5.x -> C++ OOP guidelines

Books

Guidelines for the Use of the C Language in Critical Systems

MISRA C:2012 Compliance and Interpretation

MISRA C++:2008 Practical Guide

Embedded C Coding Standards

Functional Safety and MISRA in Automotive Software

Tutorials

MISRA C:2012 rule overview

MISRA C++:2008 guidelines

Static analysis tool tutorials

Embedded software safety training

Deviation management workflow

Official Docs

https://www.misra.org.uk

https://www.misra.org.uk/Publications

Community Links

MISRA official forums

Embedded C/C++ developer groups

LinkedIn MISRA groups

Stack Overflow embedded C/C++

Industry safety-critical working groups

Community Support

MISRA official forums

Embedded C/C++ developer communities

LinkedIn MISRA groups

Stack Overflow embedded C sections

Industry-specific working groups

Monetization

Embedded software consulting

Safety-critical software auditing

Toolchain integration services

Training for MISRA compliance

Certification assistance for ISO 26262 / DO-178C

Future Roadmap

MISRA C:2025 under discussion

Enhanced coverage for modern C++ features

Better integration with static analysis tooling

Guidelines for functional safety and security

Increased adoption in automotive and aerospace

When Not To Use

Prototyping or experimental projects

Rapid application development

Non-critical software

Pure research or academic code

Projects where strict safety compliance is not required

Final Summary

MISRA C/C++ ensures safe, maintainable, and portable embedded code.

Widely used in automotive, aerospace, and safety-critical systems.

Rules can be enforced through static analysis and code reviews.

Mandatory and advisory rules guide developers to avoid undefined behavior.

Documentation of deviations is part of compliance best practices.

Faq

Is MISRA mandatory? -> Depends on industry/project safety requirements.

Does MISRA replace C coding standards? -> No, it complements them.

Is MISRA applicable to C++? -> Yes, MISRA C++ exists.

Are deviations allowed? -> Yes, if justified and documented.

Does MISRA guarantee bug-free code? -> No, it reduces risk and improves safety.

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.

Let’s Try →
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.

Let’s Try →
3

MISRA C: Rule Example (Use of const)

/* Non-compliant */
int maxValue = 100;

/* Compliant */
const int maxValue = 100;

Ensures immutability of variables where possible.

Let’s Try →
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.

Let’s Try →
5

MISRA C: Rule Example (Initialize Variables)

/* Non-compliant */
int counter;

/* Compliant */
int counter = 0;

Always initialize variables to avoid undefined behavior.

Let’s Try →
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.

Let’s Try →
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.

Let’s Try →
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.

Let’s Try →
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.

Let’s Try →
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.

Let’s Try →

Frequently Asked Questions about Misra-c-cpp

What is Misra-c-cpp?

MISRA C and MISRA C++ are coding standards developed to facilitate safety, reliability, and maintainability in embedded systems, especially in automotive, aerospace, and critical industries.

What are the primary use cases for Misra-c-cpp?

Automotive embedded software development. Safety-critical avionics code. Industrial control firmware. Medical device software. High-integrity and mission-critical systems

What are the strengths of Misra-c-cpp?

Improves code safety and robustness. Widely recognized in safety-critical industries. Enables consistent coding style across teams. Facilitates static code analysis and automated compliance. Reduces risk of undefined or dangerous behaviors

What are the limitations of Misra-c-cpp?

Learning curve for developers unfamiliar with guidelines. Can restrict some standard C/C++ idioms. May require additional tooling for enforcement. Strict rules may slow initial development. Interpretation may vary between organizations

How can I practice Misra-c-cpp typing speed?

CodeSpeedTest offers 10+ real Misra-c-cpp code examples for typing practice. You can measure your WPM, track accuracy, and improve your coding speed with guided exercises.

Learn Other Programming Languages

CReactPythonC++RustTypeScriptKotlinPHPJavaC#RubyMqlCqlN1qlCypherGremlinPartiqlHaskellElixirFsharpView all languages →
CodeSpeedTest

Improve your coding speed, code accuracy, and programming syntax WPM with practice sessions across 500+ programming languages.

Quick Links

HomeAboutFeaturesGetting StartedLanguages

Legal & Support

Pro ⚡ PricingContactPrivacy PolicyTerms of Service

Connect

CodeSpeedTest on GitHubCodeSpeedTest on TwitterEmail CodeSpeedTest

© 2026 CodeSpeedTest. All rights reserved.