Unsigned Short Int

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Deanm007
    New Member
    • Apr 2010
    • 37

    Unsigned Short Int

    How is this code giving the correct answer? I though unsigned short int is only positive numbers. I am giving it a -3 and I am getting 0 for sum.

    thanks

    Code:
    #include <iostream>
    
    using namespace std;
    
    typedef unsigned short int Ushort;
    
    int main()
    {
    	Ushort x = -3;
    	Ushort y = 3;
    
    	Ushort sum = x+y;
    	cout << sum << endl;
    
    	cin.get();
    	return 0;
    }
  • hype261
    New Member
    • Apr 2010
    • 207

    #2
    Originally posted by Deanm007
    How is this code giving the correct answer? I though unsigned short int is only positive numbers. I am giving it a -3 and I am getting 0 for sum.

    thanks

    Code:
    #include <iostream>
    
    using namespace std;
    
    typedef unsigned short int Ushort;
    
    int main()
    {
    	Ushort x = -3;
    	Ushort y = 3;
    
    	Ushort sum = x+y;
    	cout << sum << endl;
    
    	cin.get();
    	return 0;
    }
    The reason you are getting 0 for the sum is because when you set UShort x = -3 that is actually being set to the max value of a unsigned short int minus 3. Which on my system is 65533. Then you are adding 3 to it which is overflowing the unsigned short int which sets it back to 0.

    Comment

    Working...