You are viewing an old version of this page. View the current version.

Compare with Current View Page History

Version 1 Next »

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.

 Non-compliant Code Example 1

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];	} } 

Non-complaint Code Example 2

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));
  • No labels