...
Code Block | ||
---|---|---|
| ||
const float pi = 3.14159f; float degrees; float radians; /* ... */ radians = degrees * pi / 180; |
Non-Compliant Code Example
This non-compliant code example, defines a fictional version of the standard strcat()
function called strcat_nc()
. This function differs from strcat()
in that the second argument is not const
-qualified.
Code Block | ||
---|---|---|
| ||
char *strcat_nc(char *s1, char *s2);
char *str1 = "str1";
const char *str2 = "str2";
char str3[] = "str3";
const char str4[] = "str4";
strcat_nc(str1, str2); /* different 'const' qualifiers */
strcat_nc(str3, str1);
strcat_nc(str4, str3); /* different 'const' qualifiers */
|
The function behaves the same as strcat()
, but results in extraneous warnings when the second argument is a const
-qualified argument.
Compliant Solution
In this compliant solution, pi
is declared as a const
-qualified object.
Code Block | ||
---|---|---|
| ||
const float pi = 3.14159f;
float degrees;
float radians;
/* ... */
radians = degrees * pi / 180;
|
Risk Assessment
Failing to const
-qualify immutable objects can result in a constant being modified at runtime.
...