-1

This code snippet:

#include <iostream>
#include <cstddef>

int main()
{
    int a{-4}; 
    std::size_t b{3};
    std::cout << a % b;

    return 0;
}

prints

0

while this code snippet:

#include <iostream>

int main()
{
    int a{-4}; 
    int b{3};
    std::cout << a % b;

    return 0;
}

prints

-1

So, why does the first code snippet returns 0? Why does changing b from std::size_t to int print the right result?

  • 1
    Simple rule, don't mix types. And if you mix types: do cast explicitly to what you want the code to do. Do you want module of two ints or modulo of two size_t variables? Be explicit – Pepijn Kramer Nov 22 '21 at 06:43
  • 4
    Strangely similar question (also uses `-4` and `3`) posted about half an hour before this one: [Why is leetcode modulo operator of negative numbers = 0?](https://stackoverflow.com/questions/70061571/why-is-leetcode-modulo-operator-of-negative-numbers-0) – JaMiT Nov 22 '21 at 06:56
  • @JaMiT Yes, that's because I see the question, and got confused myself – justANewb stands with Ukraine Nov 22 '21 at 06:59

1 Answers1

1

Oh, it's because a implicitly converted into std::size_t becuase b is std::size_t, which is 4294967292(on my machine), and 4294967292 % 3 == 0

  • 1
    It is implicitly **converted**. There is no such thing as an implicit cast. A cast is something you write in your source code to tell the compiler to do a conversion. – Pete Becker Nov 22 '21 at 14:10