Reputation: 1267
int* test_prt(const vector<int>* array, const int index)
{
return array+index;
}
why the first argument can't be const ? under this circumstance, the "const" means what can not be modified?
Upvotes: 0
Views: 110
Reputation: 96835
array + index
is not modifying either array
or index
, it simply computes the sum between the two operands without affecting the original, so the code is working as it's supposed to. The const
here means that both the vector and index
cannot change in any way. For example, if I attempt to change one of array
s elements, I get an error:
array[0] = 5; // error! assignment of read-only value
The same applies to index
. By the way, I think your function signature should have been written as:
int* test_prt(const vector<int>& array, const int index)
{
return &array[index];
// or &array.at(index) which performs bounds checking
}
That is, we take the vector by reference and use an offset from the first element pointed to by its internal buffer. Taking by reference is essential as it avoids a copy and returning a pointer to a local copy would be Undefined Behavior. Your original code would have only worked if array
was an actual array of vectors!
And just to be clear, here's how you would call the function:
std::vector<int> v = {1, 2, 3, 4, 5};
std::cout << test_ptr(v, 1); // prints the address of the 2nd element
Upvotes: 1
Reputation: 8479
I would also remove the "const" in front of the integer. As it's an arg passed by value,
int* test_prt(vector<int> const* array, int index)
{
return array+index;
}
Upvotes: 0
Reputation: 106589
It is common to place const
after the type name, because it enables the "const to the left rule".
This is the same as what you wrote:
int* test_prt(vector<int> const* array, const int index)
{
return array+index;
}
Here, the item to the left is the vector, so this is a pointer to constant vector.
If you don't use this convention, the only special case is when const
is all the way on the left (there is nothing to the left of const), which means it applies to the thing immediately to the right of the const
.
Upvotes: 2