Saturday, December 21, 2013

What happens when an integer value goes out of range?

Signed integer variables:

Range of short int : -32,768 to 32,767
Range of long int : -2147483648 to 2147483647


Unsigned integer variables:

Range of short int : 0 to 65535
Range of long int : 0 to 4294967295

When we initialize a integer variable or assign any value to it , if the value is in range of our defined integer then the program works normally as it should.
But if the value goes out of range then there we know that the value that resides in the variable is a garbage or any random value. Is that value actually a random one?
The answer is no , that is a calculated value within the range of the integer which is calculated by the compiler.
Now, how the value is calculated of it goes outside the range and brought back in the range.

The algorithm used is:

y = x % range;
if y in range 
the value is y
else
y = y % range;


The modulus operator(%)  brings back the value gone out of range because the remainder to this expression is always in the range.

The range is taken to be the (negative end range + positive end range + 1). For unsigned variables there is no negative range so , (positive end range + 1). We have to compute the remainder by taking the nearest possible multiple of range to the value x that we assign to the integer. We can also compute the remainder by taking negative multiples if required.

Here is a video to demonstrate the process..



Sunday, December 1, 2013

Danger's associated with a protected data member in C++

We usually specify protected to data members to use them in derived class in Inheritance, but there is a problem with protected data member's that they can be used by any other class just by inheriting the class which contains that data member.
Lets watch a video to understand the problem with protected and how to fix it.