Modulo operator (%) gives different results

Given this example:

std::vector<int> numbers = {5,6,7}; //size is 3 int i = -1; std::cout << i % 3 <<"\n"; // output: -1 std::cout << i % numbers.size() << "\n"; // output: 0 

basically in both statements im processes -1% 3, but the compiler prints different numbers. I donโ€™t understand this result, maybe someone can explain it to me.

edit: like @Chris, @Keith Thompson @ AnT suggested snippet

 std::cout << std::numeric_limits<std::size_t>::max() % 3 <<"\n"; //output: 0 std::cout << i % numbers.size() << "\n"; // output: 0 

displays the expected result. Thanks for all the helpful tips!

+6
source share
2 answers

i % 3 is what you expect, and, since C ++ 11, defined semantics, but does not have a specific implementation (if I remember correctly) the result.

numbers.size() has an unsigned type ( std::size_t ). Assuming size_t is int or greater, i converted to the same unsigned type before the operation completes. The value of i gets will be the maximum value for this type, which looks divisible by 3 for you.

+8
source

The problem of% negative numbers is not defined in C ++.

0
source

Source: https://habr.com/ru/post/984258/


All Articles