Subscribe

Enter your email address:

Categories

 

February 2012
M T W T F S S
« Dec    
 12345
6789101112
13141516171819
20212223242526
272829  

Archives

Disclaimer

© 2009 Zero Intellect. All rights reserved. The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway. This material is not sponsored or endorsed by any of the vendors mentioned in this website and their Logos are trademarks of their own and their affiliates.

Exceeding the range of data types in C++

 

My friend recently gave his C++ oral examination and one of the questions asked by the invigilators was regarding incrementing a variable after it has been set to the maximum value in its range

To be specific, in his case the invigilator asked him the output of a variable of type int if initialized to 32765 and then incremented by 1

 

Sample Code

 

int i = 32765;

i++;

cout<<i;

 

Question: What is the output value of i ?

 

Now as we know the range for an integer in C++ is from -32,768 to 32,767 or from 0 to 65535

 

As per the official documentation in the Turbo C++ compiler

 

Integer data type

Variables of type int are one word in length. They can be signed (default) or unsigned, which means they have a range of -32,768 to 32,767 and 0 to 65,535, respectively

 

To demonstrate and verify the actual output, I quickly coded the program below

 

# include <iostream.h>

# include <conio.h>

 

void main()

{

   clrscr();

 

   int i = 32765;

 

   for(int j=5;j<10;i++)

   {

         j++;

         cout<<i<<”\n”;

   }

   getch();

}

 

A screenshot of the output of the sample above is as under

 

  

 

This brings us to the conclusion that the variable is incremented until the maximum value of its range (32,767) and is then reinitialized back (-32,768) to the beginning of the range automatically in a circular fashion

 

Incrementing Integer Flow

 

The diagram above gives a graphical representation of what happens when an integer is incremented after being set to the maximum value in its range

 

Happy Coding

1 comment to Exceeding the range of data types in C++

  • Shane Watson

    Interesting, I would have given a different answer if I got this question in an interview… Thanks Mate