← Back to the learning library
Before you begin: Ability to read C/C++ and compiler diagnostics. Coding guidance must match the selected language edition.
Reading time and practice time are estimates. Examples use fictional products and illustrative engineering values, not approved product limits.
Learning objectives
By the end of this module, you should be able to:
- Select coding rules appropriate to language, risk and platform.
- Configure analysis to produce useful, repeatable results.
- Triage findings and justify deviations consistently.
- Report coverage and residual findings honestly.
Lesson 1
1. A coding standard controls known sources of ambiguity
Embedded languages permit constructs that are legal but difficult to reason about or tool-dependent. A project standard should address type conversions, integer overflow, pointers, initialisation, control flow, memory use, concurrency, error handling and implementation-defined behaviour.
Adopt an established standard such as MISRA C or CERT C where it fits, then define project-specific rules. Do not copy rules that cannot be enforced or that contradict the chosen language and toolchain.
Lesson 2
2. Decide how each rule is enforced
Rules may be checked by the compiler, static-analysis tool, formatter, review checklist or architectural control. Record the enforcement mechanism and scope. Compiler warnings should be treated consistently, ideally as errors in controlled builds, with deviations documented rather than suppressed locally.
Tool configuration is part of the verification environment and must be versioned with the source.
Lesson 3
3. Triage findings by technical meaning
A finding can be a true defect, an intentional deviation, a duplicate, a tool limitation or not applicable. The disposition should explain the code context and safety or security impact. Blanket suppression hides information and makes later tool upgrades difficult.
Prioritise high-confidence defects and high-impact categories, but also review new findings relative to the baseline so the codebase does not deteriorate.
Lesson 4
4. Understand what static analysis cannot prove
Static analysis can reveal unreachable code, data-flow errors, misuse of APIs and classes of undefined behaviour. Results depend on configuration, models and analysed scope. It cannot establish correct product intent, complete timing behaviour or adequate risk control. Combine it with review and dynamic verification.
Lesson 5
5. Analyse the actual translation environment
The analyser must see the target’s integer widths, signedness, include paths, macros, language dialect and compiler extensions. Otherwise it may analyse a different program. Include generated configuration and every supported translation-unit variant that changes executable behaviour.
Document which libraries are analysed as source and which use models or summaries. An unmodelled allocator, RTOS primitive or hardware register may cause both false alarms and missed findings. Review tool assumptions when adopting a new platform or upgrading the analyser.
Do not equate tool coverage with guideline coverage. Some rules need whole-program analysis, some require knowledge of intended behaviour and some need a human review. Map each applicable rule to its enforcement method and identify uncovered obligations.
Lesson 6
6. Resolve findings at the level of meaning
Suppose a receive function reports a signed length and a caller converts it to an unsigned size. A negative error result may become a large positive length. The fix is to distinguish error from valid length before conversion, not to cast again until the warning disappears.
/* Illustrative only: validate signed results before use as sizes. */
int received = read_frame(buffer, sizeof buffer);
if (received < 0) {
report_receive_failure();
return;
}
size_t length = (size_t)received;
if (length > sizeof buffer) {
report_contract_failure();
return;
}This example assumes the read function itself respects the buffer capacity. A caller-side check cannot undo an overwrite that already happened. Review both sides of the API contract and verify the negative path.
Lesson 7
7. Make deviations narrow and reviewable
A deviation should identify the rule and edition, exact code scope, necessity, alternatives, hazards or weaknesses, compensating controls, verification and approver. State which future changes invalidate it. A pointer cast required for one memory-mapped register does not justify a repository-wide suppression.
Separate defects, justified deviations and tool false positives in reporting. Track new findings and ageing unresolved issues, not just a net total that can improve when analysed scope shrinks. Baseline legacy findings with an explicit remediation plan while preventing new unreviewed violations.
Before a release, reconcile source revision, tool version, configuration, analysed scope, remaining findings and manual-rule reviews. A green report from last week is not evidence for a different build configuration today.
Decision guide
How should a rule violation be handled?
| Disposition | Required basis | Control |
|---|---|---|
| Correct | The construct is unnecessary or defective. | Normal reviewed change and regression tests. |
| Deviate | Use is justified and risk understood. | Local rationale, approval and bounded scope. |
| Suppress as tool limitation | Finding does not represent executable behaviour. | Specific suppression with tool/version reference. |
Worked example
Worked example — unsigned arithmetic wrap
A timer expiry uses “now greater than start plus timeout”, which fails when the counter wraps.
The coding rule requires elapsed-time comparison using modular unsigned subtraction. Static analysis flags mixed signedness and potential wrap. The implementation uses a reviewed time abstraction and boundary tests around the maximum counter value.
The correction addresses the semantic defect; the team does not merely silence the overflow warning.
Engineering evidence
What should the work produce?
Coding standard
Defines adopted and project-specific rules.
Compliance matrix
Maps rules to tools or review mechanisms.
Analysis report
Records tool version, configuration, scope and results.
Deviation record
Explains, approves and traces justified exceptions.
Common failure patterns
What goes wrong?
- Chasing a zero-warning dashboard by suppressing difficult findings.
- Using default tool configuration without target and compiler models.
- Treating MISRA compliance as proof of safe behaviour.
- Allowing generated or third-party code to distort project metrics without separate treatment.
Applied exercise · approximately 25 minutes
Triage a legacy analysis backlog
A project has 600 findings: 20 possible memory errors, 200 generated-code warnings, 300 style findings and 80 low-level casts. Delivery is due in four weeks.
- Define a risk-based triage order without assuming entire categories are harmless.
- Specify the evidence needed for one hardware-access deviation.
- Choose three metrics that cannot be improved merely by suppressing findings.
Review a suggested approach
Investigate credible memory defects first, especially at external interfaces and shared buffers. Review generated-code scope and generator configuration rather than excluding it wholesale. Classify the casts by actual necessity and language behaviour; some may be bugs. Style findings may be lower priority, but any mandatory obligation needs a disposition.
A register-access deviation should name the address alignment, object representation, compiler assumptions, constrained wrapper and target test. Useful metrics include analysed translation-unit coverage, unresolved high-impact findings by age and completed manual-rule reviews. Preserve suppression/deviation counts alongside the headline result so reduced visibility is not mistaken for improved code.
Completion criteria
- Triage is technical and risk-based, not only numerical.
- Generated and low-level code remain controlled.
- Release reporting records limitations and justified exceptions.
This is a self-directed engineering exercise, not an accredited examination. Compare the rationale as well as the final answer.
Practical check
Questions for your next design review
- Is every mandatory rule paired with an enforcement method?
- Are compiler and analyser configurations controlled?
- Are new findings prevented from entering the baseline?
- Do deviations explain technical and risk implications?
- Are analysis limitations stated in the report?
Coding rules and tools reduce avoidable uncertainty when their scope, enforcement and limitations are explicit.
References and further reading
Educational guidance only. Apply the authorised standards editions, regulations and approved procedures relevant to your product and market. Linked publications support further study; the fictional exercises do not demonstrate compliance.
