Hey, quick question. I'm doing a program putting in the long max plus one and the min minus one, but I keep getting an error and am not sure what the problem is. My line for this is:
std::cout<< "The long max is: " <<std::dec<<(LONG_MAX)+1 << std::endl;
Yes, that's what I'm getting. That makes sense though. I'm wondering if I'm misunderstanding what is being asked, because I haven't seen anyone else having this problem. The question is
"Now, print the decimal (base 10) values of adding one to each variable containing the maximum numbers and subtracting one from the variables containing the minimum values (even zero for unsigned)."
Is there something I am misreading in this?
This code does not have any variable: std::cout<< "The long max is: " <<std::dec<<(LONG_MAX)+1 << std::endl;
Compare this:
1 2 3 4 5
long test = LONG_MAX;
cout << "test = " << test << endl;
test++;
cout << "test + 1 = " << test << endl;
The second version defines a variable called "test". This is given the initial value of LONG_MAX.
Its value is displayed, one is added to the variable and it is displayed again.
The difference is that in the original code, the addition is done at compile-time and the overflow is reported by the compiler as a warning or an error.
In the second version, the addition is done at run-time. There is still an overflow, but it will take place 'silently'.
One last thing. I got it to work, so based on what was said earlier, should my answer for the long max + 1 result in the long min (-9223372036854775808)?
It's undefined behavior, so it could be anything. Most compilers I've seen will simply overflow to the lowest possible value, but that's not something you can or should depend on.
Yes, that sounds right.
It's just a matter of how the binary values which are used internally are interpreted as either a positive or negative number. So yes, the largest positive number will overflow to give the largest negative number (when using signed values).
Look at it in terms of the binary values - using just 3 bits here: