简体   繁体   中英

overflow numbers in C++ (Visual Studio 2013)

I have a simple program:

#include "stdafx.h"
#include <iostream>
using namespace std;


int _tmain(int argc, _TCHAR* argv[])
{
    unsigned short a;
    cin >> a;
    cout << a;
    return 0;
}

When I input a number larger than 65535 (an overflow number), I always receive 52428 as the output. When I input a number smaller than 0 (an underflow number), the output is as expected (for example: the input -1 will have the output 65535).

I am using Visual Studio 2013 Ultimate, my friend is also using Visual Studio 2010 to compile this program and we both have the same result as above.

So what is exactly going on with the numbers larger than 65535 (the overflow numbers)?

Thanks in advance.


Hello, I found two other topics may help you out:

How does an uninitiliazed variable get a garbage value?

garbage values in C/C++

Thank you all of you for answering my question.

52428 is CCCC in hex; it's likely that it's using debug memory for the value. If you compile and run with the Release configuration you may get different results since it's truly uninitialised.

It is better to check correctness of input this way:

std::cin >> a;
if (std::cin.fail())
  std::cout << "Error!\n";
else
  std::cout << "Valid.\n";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM