confused by handling of data type

This is a discussion on confused by handling of data type within the C++ Programming forums, part of the General Programming Boards category; I have a question regarding data types 1. This code unsigned short num=65535; cout << num+2 << endl; outputs 65537 ...

  1. #1
    Registered User
    Join Date
    Aug 2001
    Posts
    84

    confused by handling of data type

    I have a question regarding data types

    1. This code
    unsigned short num=65535;
    cout << num+2 << endl;

    outputs 65537 . I expected it to output 1 because of the value
    wrapping around itself if you get my meaning. Does the cout
    object have an ability to change to a more suitable data type?
    Can anybody shed some light?

    Thanks!

  2. #2
    geek SilentStrike's Avatar
    Join Date
    Aug 2001
    Location
    NJ
    Posts
    1,141
    It gets promoted to an integer to do the addition. If you force it back into an unsigned short, you will get the wrapping effect.

    Code:
    #include <iostream>
    using namespace std;
    
    int main() {
    	unsigned short num=65535;
    	cout << num+2 << endl;
    
    	cout << (unsigned short) (num+ 2) << endl;
    	return 0;
    }
    Prove you can code in C++ or C# at TopCoder, referrer rrenaud
    Read my livejournal

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to make our own data type ?
    By Masterx in forum C++ Programming
    Replies: 6
    Last Post: 11-21-2008, 04:04 AM
  2. how do you resolve this error?
    By -EquinoX- in forum C Programming
    Replies: 32
    Last Post: 11-05-2008, 03:35 PM
  3. failure to import external C libraries in C++ project
    By nocturna_gr in forum C++ Programming
    Replies: 3
    Last Post: 12-02-2007, 02:49 PM
  4. return a random data type?
    By Niara in forum C++ Programming
    Replies: 3
    Last Post: 10-25-2005, 12:58 PM
  5. Dimension Data Type
    By ivandn in forum C Programming
    Replies: 1
    Last Post: 01-27-2005, 05:02 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21