Skip to end of metadata
Go to start of metadata

The C Standard defines octal constants as a 0 followed by octal digits (0 1 2 3 4 5 6 7). 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:

i_array[0] = 2719;
i_array[1] = 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:

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 assignments.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

DCL18-C

Low

Unlikely

Low

P3

L3

Automated Detection

Tool

Version

Checker

Description

Astrée19.04octal-constantFully checked
Axivion Bauhaus Suite6.9.0CertC-DCL18
CodeSonar5.0p0LANG.TYPE.OCOctal constant
Klocwork2018MISRA.TOKEN.OCTAL.ESCAPE
MISRA.TOKEN.OCTAL.INT

LDRA tool suite 9.7.183 SFully Implemented
Parasoft C/C++test
10.4.2

CERT_C-DCL18-a
CERT_C-DCL18-b

Octal and hexadecimal escape sequences shall be terminated
Octal constants (other than zero) shall not be used

Polyspace Bug Finder

R2018a

MISRA C:2012 Rule 7.1

Octal constants shall not be used

PRQA QA-C
 9.5

0339
1272


PVS-Studio

6.23

V536
RuleChecker
19.04
octal-constantFully checked
SonarQube C/C++ Plugin
3.11
OctalConstantAndSequence

Related Guidelines

MISRA C:2012Rule 7.1 (required)




4 Comments

  1. Victor, this looks like a good rule to work on. Comments:

    • I emailed an announcement a few days ago with some style guidelines...please study them and have the rule conform to them.
    • Your code should be expressed as non-compliant code example + compliant solution...should be fairly simple to tweak your current code.
  2. I'm wondering how we can make this more enforceable. The NCE shows decimal constants and octal constants being assigned to different elements of an array. It would be easier to enforce that constraint. Also, we could insist that for any given variable, it can only be assigned and or compared to decimal or octal constants but not both. Opinions?

    1. You're talking as if decimal and octoal ints were actually two different types. That is, conversions between one and the other should be explicit. Sounds like a good idea to me. C99 doesn't distinguish them, of course, but a SA tool could.

      1. I think that would lead to large numbers of false positives. For example, it's not uncommon to define INT_MAX to a decimal number (e.g., 2147483647) but UINT_MAX to hexadecimal (e.g., 0xffffffff).