66 lines
2.4 KiB
Plaintext
66 lines
2.4 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Integer literals starting with a zero are octal rather than decimal values. While using octal values is fully supported, most developers do not have experience with them. They may not recognize octal values as such, mistaking them instead for decimal values.
|
|
|
|
Hexadecimal literals (``++0xdeadbeef++``) and binary literals (``++0b0101'0110'00011++``, available since {cpp}14), on the other hand, have a clear marker (``++0x++`` or ``++0b++``) and can be used to define the binary representation of a value.
|
|
|
|
Character literals starting with ``\`` and followed by one to three digits are octal escaped literals.
|
|
Character literals starting with ``\x`` and followed by one or more hexits are hexadecimal escaped literals, and are usually more readable.
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,cpp]
|
|
----
|
|
int myNumber = 010; // Noncompliant. myNumber will hold 8, not 10 - was this really expected?
|
|
|
|
char myChar = '\40'; // Noncompliant. myChar will hold 32 rather than 40
|
|
----
|
|
|
|
=== Compliant solution
|
|
|
|
[source,cpp]
|
|
----
|
|
int myNumber = 8; // Use decimal when representing the value 8
|
|
// or
|
|
int myNumber = 0b1000; // Use binary or hexadecimal for a bit mask
|
|
|
|
char myChar = '\x20'; // Use hexadecimal
|
|
// or
|
|
char myChar = '\n'; // Use the common notation if it exists for the literal
|
|
----
|
|
|
|
=== Exceptions
|
|
|
|
* Octal values have traditionally been used for user permissions in Posix file systems, and this rule will ignore octal literals used in this context.
|
|
* ``'\0'`` is a common notation for a null character, so the rule ignores it.
|
|
* Since {cpp}23, an octal escape sequence can also be written `\o{123}`. Since this notation is explicit, the rule ignores it too. See S7040.
|
|
|
|
== Resources
|
|
|
|
=== External coding guidelines
|
|
|
|
* MISRA {cpp}:2023, 5.13.3 - Octal constants shall not be used
|
|
* MISRA C:2012, 7.1 - Octal constants shall not be used
|
|
* MISRA {cpp}:2008, 2-13-2 - Octal constants (other than zero) and octal escape sequences (other than "\0") shall not be used
|
|
* https://wiki.sei.cmu.edu/confluence/x/atYxBQ[CERT, DCL18-C.] - Do not begin integer constants with 0 when specifying a decimal value
|
|
|
|
=== Related rules
|
|
|
|
* S7040 - Escape sequences should use the delimited form (\u{}, \o{}, \x{})
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
include::../message.adoc[]
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::../comments-and-links.adoc[]
|
|
|
|
endif::env-github,rspecator-view[]
|