-5

I was working on a practice coding question on leetcode in c++, and I found that using the modulo operator on negative numbers returned 0 when it should not be returning 0. For context, I was testing -4 % 3, which returns 0. Does anyone know why this happens?

Here is my code:

#include <iostream>
#include <vector>

int main()
{
    std::vector<int> vec {1,2,3};
    int k{4}; 
    std::cout << (-k) % vec.size();

    return 0;
}

This prints:

0
  • 2
    Welcome to Stack Overflow. Please paste your actual code in the question, not just a screenshot of code, and provide a [mre]. – jtbandes Nov 22 '21 at 06:19
  • -4% 3 returns -1 as it should which can be seen [here](https://onlinegdb.com/w0SOZ5Iqi) – Jason Nov 22 '21 at 06:19
  • Posting only a screenshot won't help much. Provide at least minimal lines of code so that others can help you – digito_evo Nov 22 '21 at 06:22
  • 2
    *I was working on a practice coding question on leetcode in c++* -- You should practice coding with your own compiler setup on your machine, and not rely on a website's random set of questions to learn how to write C++. – PaulMcKenzie Nov 22 '21 at 06:29

1 Answers1

2

It is because in C++ when one operand of operator % is unsigned long long then other operand is also converted to it.

Unsigned number can not be negative.

So int -4 is implicitly converted to unsigned long long 18446744073709551612 that happens to divide by 3.

Öö Tiib
  • 10,809
  • 25
  • 44