Ruben23630 Ruben23630 -4 years ago 158
C Question

Unexpected result of size_t modulo long unsigned int

In the following code,

BITS_IN_INT
is an
long unsigned int
with value
32
. Why does the modulo operation return the value
0
instead of the expected
20
?

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define BITS_IN_INT sizeof(int) * CHAR_BIT

int main()
{
size_t i = 20;

printf("%zu\n", i);
printf("%lu\n", BITS_IN_INT);
printf("%lu\n", i % BITS_IN_INT);
return 0;
}

Answer Source

After macro expansion, the last printf looks like:

printf("%lu\n", i % sizeof(int) * 8);

So, the expression (in printf) is evaluated as if:

(i % sizeof(int)) * 8

If sizeof(int) is 4 (which seems to the case on your platform) then i % sizeof(int) yields 0; 0 * 8 is 0.

Avoid macros if you can. If not, always use parentheses around your macros:

#define BITS_IN_INT (sizeof(int) * CHAR_BIT)

NB: %zu is the correct format specifier for printing size_t values.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download