If an attempt is made to modify an object defined with a
const-qualified type through use of an lvalue with non-
const-qualified type, the behavior is undefined.
There are existing compiler implementations that allow
const-qualified objects to be modified without generating a warning message.
Avoid casting away
const qualification because doing so makes it possible to modify
const-qualified objects without issuing diagnostics. (See EXP05-C. Do not cast away a const qualification and STR30-C. Do not attempt to modify string literals for more details.)
Noncompliant Code Example
This noncompliant code example allows a constant object to be modified:
The first assignment is unsafe because it allows the code that follows it to attempt to change the value of the
i are declared as automatic variables, this example compiles without warning with Microsoft Visual Studio 2013 when compiled in C mode (
/TC) and the resulting program changes the value of
i. GCC 4.8.1 generates a warning but compiles, and the resulting program changes the value of
i are declared with static storage duration, this program compiles without warning and terminates abnormally with Microsoft Visual Studio 2013, and compiles with warning and terminates abnormally with GCC 4.8.1.
The compliant solution depends on the intent of the programmer. If the intent is that the value of
i is modifiable, then it should not be declared as a constant, as in this compliant solution:
If the intent is that the value of i is not meant to change, then do not write noncompliant code that attempts to modify it.
Modifying constant objects through nonconstant references is undefined behavior.
|Axivion Bauhaus Suite|
MISRA C 2004 Rule 11.5
|LDRA tool suite|
|582 S||Fully implemented|
A cast shall not remove any 'const' or 'volatile' qualification from the type of a pointer or reference
|Polyspace Bug Finder|
|Writing to const qualified object||Object declared with a |
Key here (explains table format and definitions)
|CERT C Secure Coding Standard||EXP05-C. Do not cast away a const qualification||Prior to 2018-01-12: CERT: Unspecified Relationship|
|CERT C Secure Coding Standard||STR30-C. Do not attempt to modify string literals||Prior to 2018-01-12: CERT: Unspecified Relationship|
|[ISO/IEC 9899:2011]||Subclause 6.7.3, "Type Qualifiers"|