I am trying to learn the basic of how numbers are stored in computer memory. Hence I've picked up C++ recently. I wrote this following function, to calculate the square of any int value.
// since integer can go upto 65K value, hence the return
// value is double to accomodate the square of highest int value.
double square(int val) {
return val*val;
}
Why is it giving me a wrong answer for 65535
, which as per my understanding is the largest number that can be stored in the variable of type int
? I've also discovered that there are things like:
std::numeric_limits<int>::max()
which gives me 2147483647
. This in turn confused me even more, but I am seeking an explanation for why my square
function is failing.
Edit
For 65535
my g++
compiler is giving me: -131071
.