2

I was doing an exercise for a class and I decided to see what would happen if I type in a char when the code was expecting an int. I put in the letter 'g' just to see what would happen... it output -858993460 and I have no idea why.

Here is the code:

#include <iostream> 
#include <iomanip>
#include <string>      
using namespace std;

int main()
{
int test;

 cout << "Please enter a even integer or a odd integer. " << endl;

 cin >> test;
 cout << test; //here is where i got the -858993460



 if (test % 2)
 {cout << "TRIANGLE" << endl;}
 else
 {cout << "SQUARE" << endl;}



 return 0;

 }

So where does that -858993460 come from?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • 1
    -858993460 is 0xcccccccc in hex. It does mean that `int` is uninitialized in Visual Studio debug mode. – Marco167 Mar 27 '17 at 04:41
  • -858993460 = 0xCCCCCCCC which means [you've accessed uninitialized memory](https://stackoverflow.com/q/370195/995714) – phuclv Aug 18 '18 at 11:08

2 Answers2

3

The behavior of std::basic_istream::operator>> changed from C++11. Before C++11,

If extraction fails (e.g. if a letter was entered where a digit is expected), value is left unmodified and failbit is set.

This seems to be the case. test is not initialized; then you got a random value printed out. Note that this is undefined behavior in fact.

And since C++11,

If extraction fails, zero is written to value and failbit is set.

That means you'll get the value 0 after C++11.

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • Oh! okay, so, -858993460 a default\random value and nothing was assigned to `test`. this makes sense! Thank you so much! – Chris Douglas Mar 27 '17 at 06:14
1

If you check the result of the read, you'll see that nothing was read.

if (cin >> test) {
    cout << "read " << test << endl;
}
else {
    cout << "read failed" << endl;
}

The value you're printing is test's uninitialized value. It can change from run to run. Technically, printing it is undefined behavior, so your program could even crash, although that's unlikely to happen in practice.

John Kugelman
  • 349,597
  • 67
  • 533
  • 578