Recently I discovered that if I using the mod operator with a negative number and .size() gives me some unexpected outputs…
With code such as that below, I am getting an i value of 6 but a j value of -3, my understanding is that they should both be -3? can someone help explain? Thanks
#include
#include
int main () {
std::vector<int> arr = {1, 2, 3, 4, 5, 6, 7};
std::cout << "array size: " << arr.size() << 'n';
int i = -3 % arr.size();
int j = -3 % 7;
std::cout << "i: " << i << " j: " << j << 'n';
return 0;
}
New contributor
Alex Burde is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.