Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array as const pointer

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.

like image 457
Asher Saban Avatar asked Oct 01 '10 13:10

Asher Saban


4 Answers

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.

like image 135
Prasoon Saurav Avatar answered Oct 08 '22 23:10

Prasoon Saurav


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.

like image 41
MSalters Avatar answered Oct 08 '22 22:10

MSalters


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.

like image 29
reko_t Avatar answered Oct 08 '22 22:10

reko_t


You don't increment the array in main(), you increment the local variable (parameter) in Increment()

like image 33
Adam Trhon Avatar answered Oct 08 '22 23:10

Adam Trhon