Reputation: 137
Let's say I have this program:
const int width = 4;
void test(int&){}
int main() {
test(width);
}
This will fail to compile. I notice that constant values ( also enumeration constants ) with names ( such as width ) cannot be passed by reference. Why is that so?
Upvotes: 0
Views: 119
Reputation: 514
Passing by reference allows us to change the actual object.
If an object is defined as const
, it cannot be changed. That is exactly what const means - it's constant.
Upvotes: 0
Reputation: 182753
Imagine this:
void test (int& j) { j++; }
If test
does change the value of the thing referenced, clearly we can't call it with a const parameter. And if it doesn't, why does it take its parameter by non-const reference?
Upvotes: 11