Discussion:
A8P1 ignore const?
(too old to reply)
river yu
2010-11-12 05:13:00 UTC
Permalink
Given:

int *histogram(const int *a, int n, int *m);

So are we not expected to modify "a" ?
David Xingliang Lou (CS 137 Tutor)
2010-11-12 15:02:59 UTC
Permalink
Post by river yu
int *histogram(const int *a, int n, int *m);
So are we not expected to modify "a" ?
Short answer:
You CAN modify 'a' itself, but you CAN'T modify what 'a' points to.

Long answer:
If you really want to know how the word 'const' is used, then let me
confuse you a little.

Consider these functions.

void foo(const int *a);
void foo(int *const a);

Depending on where the 'const' is placed, they mean different things.

"const int *a" means that the "pointee" is constant. In this case,

*a = 0; is BAD
*(a + 1) = 0; is BAD

but

a = 0; is GOOD (you shouldn't need to modify 'a' itself for this
assignment, though)

But on the other hand...

"int *const a" means that the pointer itself is constant, but you CAN
modify the pointee, So,

*a = 0; is GOOD
*(a + 1) = 0; is GOOD
a = 0; is BAD

If you want both the pointer and the pointee to be constant, then you
need to say

void foo(const int *const a)

Loading...