Is it safe to pass array as argument to function ? As the third party function can explore other elements than the one they meant for

715 views c++
-1

void tenTimes(int n) {
      return 10*n;
}

void tenTimesVector3(int *vector) {
      vector[0] = tenTimes(vector[0]);
      vector[1] = tenTimes(vector[1]);
      vector[2] = tenTimes(vector[2]);   
}

Here we are passing one element to the function but using that they are accessing all elements.

answered question

What is the question? This code doesn't work.

Hi Varun, welcome to Stack Overflow! Please take some time to read through our guidelines on how to ask a good question. Currently I am failing to understand what your question means... it would help if you could clarify it. Thanks!

It will only work when your function signature of tenTimesVector is void tenTimesVector3(int *vector).

1 Answer

1

If you worry about the mutability of your buffer, then in general yes, it's not "safe" to pass a non-const reference to your buffer into a function. As you noted, the function can modify any array element.

If the function is const correct (it accepts a const reference or pointer), then you can be fairly certain it won't modify your array by accident. A compiler will catch any attempt at modification. Of course, the function can cast away the const and do nasty things, const here will offer some protection from Murphy, not from Machiavelli.

The only way to be absolutely positive a function won't modify your data is to not let it reference it. If you are genuinely concerned, you can just pass it a copy:

std::vector<int> data_we_want_to_keep(3);
// ...
std::vector<int> copy_of_data = data_we_want_to_keep;
tenTimesVector3(copy_of_data.data());

Now the function will not be able to modify data_we_want_to_keep itself, despite needing access to whatever values in that buffer.

Quite often though, code is written to be well behaved. If a function accepts a const reference or pointer to your data, you can be reasonably assured it will only read it.

posted this

Have an answer?

JD

Please login first before posting an answer.