I have the following code where I have an array. I add a large number to that array, but when printing it, it shows a smaller, incorrect value. Why is that, and is there a way to fix this?
int x[10];
x[0] = 252121521121;
printf(" %i " , x[0]); //prints short wrong value
Your number requires 38 bit. If your platform’s
intisn’t that big (and there’s no reason it should be), the number simply won’t fit. (In fact, even the int literal should already have triggered a compiler warning, supposing that this is C or C++.)You could always use a data type of guaranteed size, like an int64 or something like that, depending on your language and platform. Probably no need for arbitrary-precision libraries here.
In C,
includeuse<stdint.h>and useint64_t, or justlong long int, and make sure you initialize it from a long long integer literal, e.g.252121521121LL. (Long longs are only officially part of the most recent language standards, I might add.)(Edit:
long long intis guaranteed to be at least 64 bit, so it should be a good choice.)