Consider the following code:
void Increment(int *arr) {
arr++;
}
int main() {
int arr[] = {1,2,3,4,5};
// arr++ // illegal because its a const pointer
Increment(arr); // legal
}
My question is if arr
is a const pointer, how come I can send it to a function that doesn't receive a const pointer?
The code compiles without the warning of discarding const qualifiers.
My question is if arr is a const pointer, how come i can send it to a function that doesn't receive a const pointer?
arr
(inside main()
)is not a const pointer, it is an array. An array type decays into a pointer type when passed to a function.
arr
(parameter) inside Increment
holds a copy of the address of the argument arr
(passed by value from main()
).
// arr++ // ileagal because its a const pointer
It is illegal because arr
is a non-modifiable lvalue
.
Don't get fooled by the pointer. The same holds for plain ints:
const int a = 42;
int b = a; // How can I assign a const int to a non-const int?
int c = 4; // Come to think of it, the literal 4 is a constant too
void foo (int x) { std::cout << x; }
foo(a); // How come I can call foo with a const int?
In summary, const
applies to each object individually. A copy of a const object doesn't need to be const too.
The reason why you can't increment int arr[]
in main
is because it's not modifiable lvalue. The standard says:
A modifiable lvalue is an lvalue that does not have array type, does not have an incomplete type, does not have a const-qualified type, and if it is a structure or union, does not have any member (including, recursively, any member or element of all contained aggregates or unions) with a const-qualified type.
The increment operator ++
requires a modifiable lvalue (as it modifies). However the pointer in the Increment
function is a modifiable lvalue (it's not of an array type, it's a pointer), which is why it's legal in there.
You don't increment the array in main(), you increment the local variable (parameter) in Increment()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With