0

For example:

#include <stddef.h>
#include <stdlib.h>
#include <stdio.h>

int main(int argc, char **argv)
{
    int a = (int) strtol(argv[1], (char**) NULL, 10);
    int b = (int) strtol(argv[2], (char**) NULL, 10);

    printf("%d %% %d = %d\n", a, b, a % b);
    return (0);
}

(the program takes the values as command line arguments because when hard-coded I think -2147483648 % -1 gets replaced with 0 at compile time)

Running this simple program with -2147483648 and -1 as the first and second argument respectively raises a SIGFPE. Why does this happen? Is there other special cases like it? How can I avoid it?

Thanks!

nasso
  • 603
  • 5
  • 13
  • 1
    Given a 32bit `int`, `2147483648` cannot be represented in it, so how do you want to divide `-2147483648` by `-1` ? – Sander De Dycker Oct 14 '19 at 09:12
  • `-2147483648` is representable by an integer though? Plus it's a modulo, not a division? – nasso Oct 14 '19 at 09:13
  • 3
    @nasso `x % y` means to get the remainder when dividing `x / y`. If the division doesn't exist, neither does the remainder. – Barmar Oct 14 '19 at 09:14

0 Answers0