If I leave out the (signed int) recast for uInt then the comparison does not work. Is this because when an unsigned int is compared to a negative signed int, the comparison assumes since the left side of the logical operand is unsigned, then the right side is also unsigned?
I think it is your answer that is retarded. You didn't even read my question. I never said an unsigned integer could be negative, and you clearly don't know enough about C++ to answer my question of why the logical comparison in this case does not work.
I think that you are correct -- the -1 is promoted to an unsigned integer.
However, I do have to wonder why you are doing this comparison; either way (signed or unsigned) the comparison will always be true (or false) except when uInt == -1.
Thanks Duoas. Obviously the example I used is grossly oversimplified, but I've seen several programs recently where people use unsigned int in their loops. I was wondering then, when is it a good idea or not a good idea to use unsigned int in loops. I found this link:
which specifically uses scenarios like (unsigned int x >=0) or (unsigned int x > -1) as one of the main dangers of unsigned int loops. (See post by Jack klein etc...). They explain it gives unexpected results, but they don't explain why. I think it's always good to understand why something does not work, rather than just "it doesn't work". It helps me to learn the language better if I know why.
I think I will always use signed int in my loops, because otherwise it seems much too easy to make mistakes like the following (which gives no compiler warning and runs fine, but also runs incorrectly):
#include <iostream>
usingnamespace std;
#define WATERFREEZE 0 //this is the original code from developer #1
#define ALCOHOLFREEZE -114 //this code was added later by developer #2
void main()
{
unsignedint Celsius;
cout << "listing all temperatures from 100 Celsius down to water freeze \n";
for (Celsius = 100; Celsius > WATERFREEZE; Celsius--)
{
cout << "Celsius reading: (" << Celsius << ") is above water freeze \n";
}
//this code added later, but no temperatures will be listed
cout << "listing all temperatures from 100 Celsius down to alcohol freeze \n";
for (Celsius = 100; Celsius > ALCOHOLFREEZE; Celsius--)
{
cout << "Celsius reading: (" << Celsius << ") is above alcohol freeze \n";
}
}
The choice of signed or unsigned depends on the loop requirements.
As for the link -- the computer doesn't actually care whether your ints are signed or not. The only difference is how you interpret the comparison. There are no efficiency losses either way.
The danger alluded to is exactly this:
(unsigned x >= 0): always true --> infinite loop
(unsigned x > -1): false unless x == INT_MAX --> failed loop (remember that unsigned(-1) is the same as INT_MAX)
As for your example, a Celsius temperature value can indeed be less than zero, so making it an unsigned value to begin with was the error (on the part of developer #1).