g++ 4.8 and clang++ 3.3 compile this without warning or error (using -Wall -Werror). In fact, we can use C++11's std::array
and its at
method to get bounds checking, and
#include <array>
int main() {
unsigned int k = 1U, seed = 12345U;
std::array<int,55> randomNumbers;
randomNumbers.at(54) = seed;
for(unsigned int i = 1U; i <= 54U; ++i) {
unsigned int ii = ((21U * i) % 55U) - 1U;
randomNumbers.at(ii) = k;
k = seed - k;
seed = randomNumbers.at(ii);
}
return 0;
}
yields no out-of-bounds accesses, as you claimed. I think your code is fine. VS is worried that the line ((21U * i) % 55U) - 1U)
may result in 0 - 1
, which will overflow because ii
is an unsigned int. If you use ints instead of unsigned ints, does VS still complain?
(Using Python, your index mapping seems fine:
>>> sorted([21*n % 55 - 1 for n in range(1,55)])
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53]
There shouldn't be any out-of-bounds errors, especially since you won't "reach" -1 using unsigned ints.)