0

I'm currently taking an introductory C++ class and the professor gave us the following example:

unsigned int TEST = -1;
cout << TEST;

Now, on his machine, TEST is returned as the maximum value for an integer, because he forced underflow. But on my machine, it is returned as 0.

Is this behavior compiler dependent or anything? In other words, why did my machine return 0 but his machine return the maximum?

ohitsanazn
  • 238
  • 1
  • 3
  • 12
  • 1
    What compiler and which compilation flags did you use? – myaut Jan 30 '17 at 22:40
  • 2
    This is not a duplicate, but likely an incomplete code. – koalo Jan 30 '17 at 22:43
  • @myaut I used clang++ main.cpp -o main, whereas the professor was using powershell + cl – ohitsanazn Jan 30 '17 at 22:47
  • Cannot reproduce with clang++ 3.7 on Linux/x86_64, it gives me `4294967295`... – myaut Jan 30 '17 at 22:49
  • 1
    Please see [ask] and provide a [mcve]. And that's not underflow, but conversion signed to unsigned. In C it is well defined and indeed should give `UINT_MAX`. Although a different language, I assume it is the same in C++. – too honest for this site Jan 30 '17 at 22:50
  • @πάνταῥεῖ Dupehammer abuse again? :( – Lightness Races in Orbit Jan 30 '17 at 23:07
  • I'd double check this in the debugger, sometime stdout can results can get confusing. I'd also add a string and an endl to make sure you're getting the result you want like `cout << "TEST = " << TEST << endl;` – MrEricSir Jan 30 '17 at 23:09
  • What happens if change the var name TEST to something different e.g. test or asdf? – 4xy Jan 30 '17 at 23:35
  • The term *underflow* is typically used to designate a floating-point phenomenon, whose nature is completely different from what your example attempts to illustrate. What you have there is still *over*flow. One can call it *negative overflow* or something like that, but not *underflow*. – AnT stands with Russia Jan 30 '17 at 23:40

1 Answers1

6

Is this behavior compiler dependent

No. It is platform dependent in the sense that the maximum value of unsigned int may vary between platforms. But all standard compliant compilers will show the largest value representable by unsigned int - which is never 0.

why did my machine return 0 but his machine return the maximum?

Two possible options are: This is not the program that produced the output on your machine, or the compiler on your machine is borked.

eerorika
  • 232,697
  • 12
  • 197
  • 326