When a variable, array, or pointer is declared as const, do not attempt to modify it.
The specification of const in variables and parameters implies to a maintainer or caller that, despite knowing some memory location, the code will not modify its content. Although C allows you to remove the specifier using typecasts, doing so violates the implication of the specifier.
In the following example, f() is passed a const char pointer. It then typecasts the const specification away, and proceeds to modify the contents.
void f(const char *str, int slen) { char *p = (char*)str; int i; for (i = 0; i < slen && str[i]; i++) { if (str[i] != ' ') *p++ = str[i]; }Â }Â |
In this example, a const int array vals is declared, and then it's content modified by calling memset with the function, leading to values of 0 in the vals array.
const int vals[] = {3, 4, 5}; memset((int*)vals, 0, sizeof(vals)); |