I was wondering why the following code returns the smallest integer?
Code:int x; for(x=1; x>0; x<<=1); printf("%d",x);
thanks.
I was wondering why the following code returns the smallest integer?
Code:int x; for(x=1; x>0; x<<=1); printf("%d",x);
thanks.
int in your case is signed. Thus, it ends up overflowing the variable, which wraps around to negative numbers. Oh, and it doesn't "return" anything. You don't have any return statements.
Quzah.
Hope is the first step on the road to disappointment.
It will actually display the 'most negative' number possible for the int data type due to integer overflow.Originally Posted by jedi_jinn
you should use 'unsigned int', however in order to display the number as unsigned, you need to use %u, not %d.
Try searching the net for 'twos-complement' for more information on how computers store numbers.
This only works on 2 complements systems.
There is a sign magnitude system (of which I cant remember the name atm ) where loading the value 0x80000000 into a variable will crash your program. On that system the variable stands for -0. So dont write code liek this. If you want to know the minimum int value use INT_MIN or INT32_MIN with a C99 compiler
Last edited by Laserve; 10-23-2006 at 01:10 AM.
To further the point, signed overflow or underflow is undefined behavior.
Quzah.
Hope is the first step on the road to disappointment.