this gives me the ans as "b is less"?? why?Code:main() { int b=1; unsigned int a=-1; if(a<=b) cout<<" a is less \n"; else cout<<"b is less \n"; }
this gives me the ans as "b is less"?? why?Code:main() { int b=1; unsigned int a=-1; if(a<=b) cout<<" a is less \n"; else cout<<"b is less \n"; }
Because on your compiler when you underflow an unsigned like that it becomes a very large number. Add
either before or after your condition and you'll see why.Code:std::cout<<"a = "<< a << ", b= "<< b << std::endl;
> unsigned int a=-1;
Unsigned and a negative number - what did you expect to happen?
If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
If at first you don't succeed, try writing your phone number on the exam paper.
He thinks that because a is unsigned, -1 will be converted to 1. which is not gonna happen Thats also what i thought when i first started programming. Those books are confusing sometimes they need more explaination.
Actually, on x86 systems, -1 for unsigned int gets converted to about 4 billion. And your compiler should give you a warning anyway, first on the unsigned initialization to a negative number, and again on the signed/unsigned mismatch in the comparison.
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
6.3.1.3 Signed and unsigned integers
1 When a value with integer type is converted to another integer type other than_Bool,if the value can be represented by the newtype, it is unchanged.
2 Otherwise, if the newtype is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the newtype until the value is in the range of the newtype.
3 Otherwise, the newtype is signed and the value cannot be represented in it; the result is implementation-defined.
Also, it's:
And unfortunatly, return 0; is implicit if not provided so this confuses some people. But yet, main returns an int and you must specify it.Code:int main() { .. }