Hacker News new | past | comments | ask | show | jobs | submit login

I've just tried a simple case in which a program prints the output of an integer division and the output of an integer addition which overflows in 32-bit integers.

   (Clue C version)
    7/3 is 2, remainder is 1
    2147483648 + 2147483649 is 1
    The sum 1 is greater than 2147483648

   (pure GCC version)
    7/3 is 2, remainder is 1
    2147483648 + 2147483649 is 1
    The sum 1 is less or equal to 2147483648

   (of program)
    #include <stdio.h>

   void show_division(int x, int y);
   void show_division(int x, int y) {
      printf("%d/%d is %d, remainder is %d\n", x, y, x/y,   x%y);
    }

   void show_add(unsigned int x, unsigned int y);
   void show_add(unsigned int x, unsigned int y) {
      unsigned int z = x + y;
      printf("%u + %u is %u\n", x, y, z);
      if( z > x ) {
        printf("The sum %u is greater than %u\n", z, x); 
      }
      else {
        printf("The sum %u is less or equal to %u\n", z, x); 
      }
   }

  int main(int argc, char* argv[]) {
     show_division(7, 3);
     show_add(0x80000000u, 0x80000001u);
     return 0;
   }
The division rounds in the expected way expected because the intermediate result is cast to integer; the addition overflows only internally in printf.

However, if you expect any particular overflow behaviour of your C integers, chances are you're not following ISO C to the letter. ISO C doesn't even guarantee two's complement representation of integers.

[edit: layout] [edit again: layout, wishing there was a preview]




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: