I was trying to create some example code in Microsoft Visual Studio which looks like that
int main()
{
const size_t size = 10;
int arr[size];
for (size_t i = 0; i < size; ++i)
arr[i] = i;
return 0;
}
Now JetBrains ResharperC++ emits the following warning in line arr[i] = i;
Do not use array subscript when the index is not an integer constant expression; use gsl::at() instead
I fail to understand what I this means and how to resolve this warning.
As this is a scheme I was using fairly often, I am a little concerned about the warning.
Could anyone advice or point me in the right direction?
EDIT: Changing the loop to:
for (size_t i = 0; i < size; ++i)
arr[i] = 0;
still produces the warning.
In general
for (size_t i = 0; i < size; ++i)
arr[i] = something;
is dangerous. You can't tell if arr[i]
is going to go out of bounds of the array. This is why the C++ Core Guidelines suggest you use gsl::at()
as it will do bounds checking to make sure you do not go out of bounds on the array.
This isn't the only solution though. If you just need to iterator over the range you can use a range based for loop like
for (const auto& e : arr)
//e is each element of the array and is not mutable here
or
for (auto& e : arr)
//e is each element of the array and is mutable here
And for a case like yours where you need to fill the array you can use std::iota
like
std::iota(std::begin(arr), std::end(arr), 0);
and all of these are guaranteed to not go out of bounds.