const can protect the pointed-to data, the pointer itself, or both. Read the declaration right to left.
| Declaration | Read as | Change *p? | Change p? |
|---|---|---|---|
int *p | pointer to int | Yes | Yes |
const int *p (= int const *p) | pointer to const int | No | Yes |
int *const p | const pointer to int | Yes | No |
const int *const p | const pointer to const int | No | No |
#include <stdio.h>
int main(void) {
int a = 1, b = 2;
const int *to_const = &a; /* read-only view */
to_const = &b; /* OK: pointer can move */
int *const fixed = &a; /* pointer is fixed */
*fixed = 10; /* OK: data can change */
const int *const both = &b;
printf("%d %d %d\n", *to_const, a, *both);
return 0;
}2 10 2int main(void) {
int a = 1, b = 2;
const int *to_const = &a;
*to_const = 5; /* error: read-only */
int *const fixed = &a;
fixed = &b; /* error: pointer is const */
return 0;
}const in function parameters
#include <stdio.h>
#include <ctype.h>
/* const promises: "I will only read the characters" */
int count_upper(const char *s) {
int n = 0;
for (; *s; s++) /* moving the pointer is fine */
if (isupper((unsigned char)*s)) n++;
return n;
}
int main(void) {
char name[] = "Hello World";
printf("%d\n", count_upper(name)); /* char * -> const char * is implicit */
printf("%d\n", count_upper("ABC"));
return 0;
}2
3What is the difference between const char *p, char const *p and char *const p?
Can a const variable be modified through a pointer?