c - Signed long integer becomes negative as it grows? -
i'm doing math, printing signed long integer so:
file1.c
#include <stdio.h> int main (int argc, char *argv[]) { long my_signed_integer = 9999l * 9999l * 9999l * 9999l; printf("this signed integer %ld.\n", my_signed_integer); return 0; }
makefile
cflags=-wall -g all: file1 clean: rm -f file1
i trying see how far go without compiler throwing me error, adding 1 more 9999l
multiplication each time, running:
make ./file1.c
to see happens.
4 times
when using 9999l
4 times (like in example above), get:
this signed integer 9996000599960001.
without warning.
5 times
using 9999l
5 times, 1 warning:
warning: overflow in expression; result 7716289630452291919 type 'long' [-winteger-overflow]
but file still compiles, , eventual result is:
this signed integer 7716289630452291919.
6 times
using 9999l
6 times, 2 warnings - 1 negative number:
warning: overflow in expression; result 7716289630452291919 type 'long' [-winteger-overflow] long my_signed_integer = 9999l * 9999l * 9999l * 9999l * 9999l * 9999l; ^ warning: overflow in expression; result -7550445434587511647 type 'long' [-winteger-overflow] long my_signed_integer = 9999l * 9999l * 9999l * 9999l * 9999l * 9999l;
alas, files still compiles, , result is:
this signed integer -7550445434587511647.
and pattern continues add more , more integers - warning every time.
first, can explain why doesn't compiler crash , refuse compile file? there's overflow - why tolerated, , other cases - such multiplying large numbers - crash it?
also, why eventual result negative integer?
overflow of signed integer types undefined behavior per c standard. compiler free generate whatever behavior wishes. means free generate warning or not.
in practice, on hosted implementation using 2's complement representation integers, overflow behave though arguments unsigned (and therefore reduced modulo 2^(bit-length)) , result interpreted signed.
in particular case seems long
64-bit type. multiplying 9999l
4 times fits within type, more , have overflow. values you're getting lowest 64 bits of result interpreted signed long
.
in case of 5 times, high order bit happens not set, result displays @ positive. in case of 6 times, high order bit set, displays negative.
Comments
Post a Comment