...
The function behaves the same as strcat()
, but results in extraneous spurious warnings when the second argument is a const
-qualified argument, as in the initial invocation strcat_nc(str1, str2)
.
Compliant Solution
In this compliant solution, pi
is declared as a const
-qualified objectThis compliant solution uses the prototype for the strcat()
from C90. Although the restrict
type qualifier did not exist in C90, const
did. In general, the arguments should be declared in a manner consistent with the semantics of the function. In the case of strcat()
, the initial argument can be changed by the function while the second argument cannot.
Code Block | ||
---|---|---|
| ||
char *strcat(char *s1, const char *s2); char *str1 = "str1"; const float pi char *str2 = "str2"; char str3[] = 3.14159f; float degrees; float radians; /* ... */ radians = degrees * pi / 180; "str3"; const char str4[] = "str4"; strcat(str1, str2); strcat(str3, str1); strcat(str4, str3); /* different 'const' qualifiers */ |
The const
-qualification of the second argument s2
eliminates the spurious warning in the initial invocation, but maintains the warning on the final invocation in which a const
-qualified object is passed as the first argument (which can change).
Risk Assessment
Failing to const
-qualify immutable objects can result in a constant being modified at runtime.
...