void AFunction(int ivar)
{
if(ivar <= -1)
{
cout<< "Invalid Answer! Enter a Valid One!";
}
else
{
//other code
}
}
Confused: Negative #'s and If statements
That code is perfectly valid, and should do as you expect. However, perhaps for some reason, ival is not what you think it is. Try sending it to cout along with your error message.
Or better, use the debugger to step through your code and check the values of variables at different points in time. The debugger is a very valuable tool. Learning to use it early on will be very useful.
Or better, use the debugger to step through your code and check the values of variables at different points in time. The debugger is a very valuable tool. Learning to use it early on will be very useful.
Surprisingly I did use the debugger. It says that the variable that is taken in is equal to 1. Thats what got me really confused, because it should skip over it.
EDIT: I just added the code to show what ivar equals. It equals 1.
EDIT #2: I kinda lied in the first post of mine. The int argument is an unsigned int. Could that be the problem? Sense unsigned variables can't hold negative numbers?
[Edited by - Koolchamp on October 6, 2006 10:16:22 PM]
EDIT: I just added the code to show what ivar equals. It equals 1.
EDIT #2: I kinda lied in the first post of mine. The int argument is an unsigned int. Could that be the problem? Sense unsigned variables can't hold negative numbers?
[Edited by - Koolchamp on October 6, 2006 10:16:22 PM]
It is quite possible that since ivar is unsigned, it is converting all numbers that are compared to it to an unsigned int as well. The bit-pattern for -1, when interpretted as an unsigned int instead of a signed int, is +4294967295 (on a 32-bit machine, using the standard 2's complement form), number that is most definitely greater than ivar, thus the if-statement would evaluate to true.
Most compilers will give you a warning about doing a signed/unsigned comparison, and the warning is because of problems just like this. Something may look fine superficially, but things are happening behind the scenes that might make it do something other than you expected.
Most compilers will give you a warning about doing a signed/unsigned comparison, and the warning is because of problems just like this. Something may look fine superficially, but things are happening behind the scenes that might make it do something other than you expected.
Quote:Original post by Koolchamp
EDIT #2: I kinda lied in the first post of mine. The int argument is an unsigned int. Could that be the problem? Sense unsigned variables can't hold negative numbers?
Yep, that's exactly it. "Unsigned" means that it doesn't have a sign (positive or negative) so unsigned numbers are always positive.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement