Eric Chamberland <eric.chamberl...@giref.ulaval.ca> writes:
> int main() {
>    int a=1741445953; // my number of unknowns...
>    int b=2*(a+2);
>    unsigned long int c = b;
>    std::cout << " a: " << a <<  " b: " << b << " c: " << c <<std::endl;
>    return 0;
> }
>
> and it gives:
>
>   a: 1741445953 b: -812075386 c: 18446744072897476230

This comes from the integer casting rules.

$ cat overflow.c
#include <stdio.h>

int main(int argc,char **argv) {
  int a=1741445953;
  size_t a1 = 2*(a+2);
  size_t a2 = 2ll*(a+2);
  printf("%zd %zd\n", a1, a2);
  return 0;
}
$ make overflow && ./overflow 
cc     overflow.c   -o overflow
-812075386 3482891910

Attachment: signature.asc
Description: PGP signature

Reply via email to