2

I want to calculate: (-15 % 3) which should be 0 but instead i'm getting 1:

When i explicitly do:

int IntFcn (const void *key, size_t tableSize)
{
    printf("%d\n",(*(int*)key)); // prints -15
    printf("%d\n",tableSize); // prints 3
    printf("%d\n",(-15) % 3); // prints 0
}

I get the right result (0) but when i try to use the variables below i get 1:

int IntFcn (const void *key, size_t tableSize)
{
    printf("%d\n",(*(int*)key)); // prints -15
    printf("%d\n",tableSize); // prints 3
    printf("%d\n",((*(int*)key) % tableSize)); // prints 1
    return ((*(int*)key) % tableSize);
}

Why is this happening?

2
  • 2
    Can you show us how you called all these functions please? Commented Dec 26, 2012 at 11:23
  • Don't printf() a size_t argument as "%d". Either cast to (unsigned int) and use a "%u" spec, or use the "%zu" specifier. Note: printf() is a varargs function, so you should be very carefull with the types of the arguments. Commented Dec 26, 2012 at 11:28

2 Answers 2

6

In your second case the second operand of modulo is unsigned integer thus the first operand is promoted to unsigned as well before performing the modulo. So the result will be (unsigned)(-15) % 3 which is equal (for 32-bit int) to 4294967281 % 3 == 1.

Sign up to request clarification or add additional context in comments.

4 Comments

how can i overcome this if i want this to work on both 32/64 bit machines?
It's not related to 32/64 bits. It's a matter of signed/unsigned arithmetic operations. Your operand is being promoted to unsigned when you don't expect it to. Cast explicitly to int to prevent the effect: ((*(int*)key) % (int)tableSize)
I would suggest that, assuming tablesize may get LARGE on a 64-bit machine [hence the use of size_t?], that using casts to long would be a better choice than int. But otherwise agree.
@MatsPetersson I agree in general. But in this case it's probably ok since key to that table is int
1

try this..

return ((*(int*)key) % (int)tableSize);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.