Example 1 — A read-only array parameter
The compiler rejects writes through a.
#include <stdio.h>
static const int LIMIT = 3;
static int sum(const int *a, int n) {
int total = 0;
for (int i = 0; i < n; i++) {
total += a[i]; /* a[i] = 0; would not compile */
}
return total;
}
int main(void) {
int v[] = {1, 2, 3};
printf("sum=%d (limit %d)\n", sum(v, LIMIT), LIMIT);
return 0;
} How It Works
const int *apromises thatsumwill not change the array.LIMITis a read-only object.- Callers can pass either const or non-const arrays safely.
