0

my_mod.cpp:

#include <iostream>
using namespace std;

unsigned int my_mod(int a, unsigned int b)
{
    int result;

    cout << "\ta\t=\t" << a << endl;
    cout << "\tb\t=\t" << b << endl;
    cout << "\ta%b\t=\t" << a%b << endl;

    result = a%b;
    if (result < 0) {result += b;}
    return result;
}

int main()
{
    cout << "-1%5 = " << -1%5 << endl;
    cout << "my_mod(-1,5) = " << my_mod(-1,5) << endl;
    return 0;
}

compiled via: g++ ./my_mod.cpp

results in:

-1%5 = -1
    a   =   -1
    b   =   5
    a%b =   0
my_mod(-1,5) = 0

What the actual hell is happening here I just can't understand what possibly could go on?! This can't be due to the global scope, right?! I mean it is exactly the same %-expression ... how can they yield 0 and -1?! (Instead of the desired 4, by the way.)

Please, if anybody can, explain this to me ... it just took me days to narrow down an error in a wider context to this. Seriously, I'm about to cry.

How can I have my (global) own modulus returning 4 in the example above??

Vicky
  • 12,934
  • 4
  • 46
  • 54

1 Answers1

3

It's because you're using an unsigned int, the signed int (-1) gets promoted to -1 % UINT_MAX so your operation becomes (-1 % UINT_MAX) % 5 = 0 (thanks to jrok for this more detailed reason)

try

cout << "\ta%b\t=\t" << a%(int)b << endl;

result = a%(int)b;

with function signature of: int my_mod(int a, unsigned int b)

Or just use a function signature of: int my_mod(int a, int b)

Matthew Mcveigh
  • 5,695
  • 22
  • 22
  • It's actualy because of integer promotion, to be pedantic. -1 promoted to `unsigned int` yields UINT_MAX which is evenly divisible by 5. – jrok Aug 30 '13 at 11:44
  • OK, now that was just as fast as it was embarrassing for me. Sorry, I don't know how I could fail to see this. I haven't slept much since this error screw things over, granted. But this is bad. Thank you very, very much! – JohnSmithOptional Aug 30 '13 at 11:48