...
Pointers behave in a similar fashion. A function may change a pointer to reference a different object, or NULL, yet that change is discarded once the function exits. Consequently, declaring a pointer as const
is unnecessary.
Code Block |
---|
void foo(int * x) {
x = NULL; /* only lasts until end of function */
/* ... */
}
|
...
Code Block |
---|
|
void foo(int * x) {
if (x != NULL) {
*x = 3; /* visible outside function */
}
/* ... */
}
|
...
Code Block |
---|
|
void foo(int const int * x) {
if (x != NULL) {
*x = 3; /* generates compiler error */
}
/* ... */
}
|
...
Code Block |
---|
|
void foo(int const int * x) {
if (x != NULL) {
printf("Value is %d\n", *x);
}
/* ... */
}
|
...
Code Block |
---|
|
char *strcat_nc(char *s1, char *s2);
char *str1 = "str1";
char const char *str2 = "str2";
char str3[] = "str3";
char const char str4[] = "str4";
strcat_nc(str3, str2); /* Compiler warns that str2 is const */
strcat_nc(str1, str3); /* Oops, attempts to overwrite string literal! */
strcat_nc(str4, str3); /* Compiler warns that str4 is const */
|
...
Code Block |
---|
|
char *strcat(char *s1, char const char *s2);
char *str1 = "str1";
char const char *str2 = "str2";
char str3[] = "str3";
char const char str4[] = "str4";
strcat(str3, str2);
strcat(str3, str1); /* Args reversed to prevent overwriting string literal */
strcat(str4, str3); /* Compiler warns that str4 is const */
|
...