The C ISO Standard defines octal constants as a 0 followed by octal digits (0 1 2 3 4 5 6 7).
This can lead to programming errors in constants that are meant to be taken by their decimal value, especially when declaring multiple constants and preserving fixed length.
Example
When declaring integer constants as in:
Programming errors can occur when decimal values are mistakenly specified as octal constants.
Noncompliant Code Example
In this noncompliant code example, a decimal constant is mistakenly prefaced with zeros so that all the constants are a fixed length:
Code Block | ||||
---|---|---|---|---|
| ||||
Code Block | ||||
i_array[0] = 2192719; i_array[1] = 042; |
The constant
Code Block |
---|
042
|
is interpreted as octal, with decimal value
Code Block |
---|
34
|
Which might or might not be what the programmer wanted.
Risk assesment
4435;
i_array[2] = 0042;
|
Although it may appear that i_array[2]
is assigned the decimal value 42, it is actually assigned the decimal value 34.
Compliant Solution
To avoid using wrong values and to make the code more readable, do not preface constants with zeroes if the value is meant to be decimal:
Code Block | ||||
---|---|---|---|---|
| ||||
i_array[0] = 2719;
i_array[1] = 4435;
i_array[2] = 42;
|
Risk Assessment
Misrepresenting decimal values as octal can lead to incorrect comparisons and assignmentsMisinterpreting decimal values as octal could lead to an incorrect value being written into code.
Rule | Severity | Likelihood | Remediation Cost | Priority | Level |
---|---|---|---|---|---|
DCL18-C |
Low |
Unlikely |
Low | P3 | L3 |
References
Automated Detection
Tool | Version | Checker | Description | ||||||
Astrée |
| octal-constant | Fully checked | ||||||
Axivion Bauhaus Suite |
| CertC-DCL18 | |||||||
CodeSonar |
| LANG.TYPE.OC | Octal constant | ||||||
Helix QAC |
| C0339, C1272 | |||||||
Klocwork |
| MISRA.TOKEN.OCTAL.ESCAPE MISRA.TOKEN.OCTAL.INT | |||||||
LDRA tool suite |
| 83 S | Fully Implemented | ||||||
Parasoft C/C++test |
| CERT_C-DCL18-a | Octal and hexadecimal escape sequences shall be terminated | ||||||
PC-lint Plus |
| 9001 | Fully supported | ||||||
Polyspace Bug Finder |
| CERT C: Rec. DCL18-C | Checks for use of octal constants (rec. fully covered) | ||||||
PVS-Studio |
| V536 | |||||||
RuleChecker |
| octal-constant | Fully checked | ||||||
SonarQube C/C++ Plugin |
| OctalConstantAndSequence |
Related Guidelines
MISRA C:2012 | Rule 7.1 (required) |
...
\[[ISO/IEC 9899:1999|cplusplus:AA. C References#ISO/IEC 9899-1999]\] Section 6.4.4.1 "Integer constants"
\[cplusplus:MISRA 04\] Section 6.7 Rule 7.1 Wiki Markup