output - arithmetic overflow because signed characters in C program -
we know signed char
can have values -128
127
. when run below program no overflow happens though l output exceeds range of signed character.
#include <stdio.h> int main() { char = 60; char j = 30; char k = 10; char l = (i*j)/k; printf("%d ", l); return 0; }
the output of
l
180
out of rangechar l
, not getting error.
in other scenario if take same program instead of arithmetic function if put l=180
, try print wrong answer.
#include <stdio.h> int main() { char = 60; char j = 30; char k = 10; char l = 180; printf("%d ", l); return 0; }
the answer in 2nd case -76
. can explain why? if virtually executing same thing getting different result.
are sure did , test described in first snippet? if run, overflows wraps around expected.
it makes big difference if did
char l = (i*j)/k; printf("%d ", l);
and if did
printf("%d ", (i*j)/k);
as in second case, compiler infer usage of int
output, (the result not fit inside char without wrapping around obviously), , because intermediate computations made in int
, not char
.
in addition, consider result fits inside unsigned char
, check case too.
in case, start thinking cases of problematic compiler too, after sure program executed should do.
Comments
Post a Comment