c - Variable (short) changes values when copied/assigned -
i have following code:
short num_short = 1; int possible_new_short = 1; valid = 1; while (valid) { possible_new_short = num_short * 10; printf("----\n"); printf("num short: %d\n", num_short); printf("possible new short: %d\n", possible_new_short); if (possible_new_short % 10 == 0) { num_short = possible_new_short; printf("new! %d\n", num_short); } else { valid = 0; } if (num_short == 0) { valid = 0; } } printf("num_short: %d\n", num_short);
the output follows:
---- num short: 1 possible new short: 10 new! 10 ---- num short: 10 possible new short: 100 new! 100 ---- num short: 100 possible new short: 1000 new! 1000 ---- num short: 1000 possible new short: 10000 new! 10000 ---- num short: 10000 possible new short: 100000 new! -31072 ----
as can see, value of possible_new_short
100000
, when reassigned num_short
goes -31072
. why happening?
i'm new c , guess num_short
variable overflowed. because num_short
, possible_new_short
stored in different slots of memory, 1 can overflow , 1 can't?
what best practices guard against this?
your guess correct, num_short
of type short
, 16-bit in machines today.
a 16-bit signed integer can hold values @ 215 − 1, 32767
. last value 100000
overflows.
possible_new_short
doesn't overflow because type int
. in general, think maximum possible values variable holds, , define type accordingly. example, can use long
or long long
instead.
Comments
Post a Comment