0
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?

2
  • 1
    Are you sure you want to pass that std::vector as a pointer? Commented Jul 3, 2013 at 2:27
  • 1
    Won't compile: array+index has the same type as array and can't be converted to the return type int*. Commented Jul 3, 2013 at 2:29

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

The rule-of-thumb is const applies to the thing to the left of it. If there is nothing to the left of it, it applies to the leftmost thing.
so in this case, what the pointer point to can not be modified, but the pointer itself can move?
@nzomkxia, Yes, though since it isn't, I'd recommend making it const as well.
1

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 arrays 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 

Comments

0

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; } 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.