|
-
March 7th, 2011, 12:50 AM
#1
anomalous loop behavior
Hi. Im an economics undegrad who knows a bit of C and is baffled by something I tried out.
I was looking up C's data types. Im interested in unsigned char for a moment. Heres what I tried (forgive me if Im supposed to enclose code in some special enclosure, im unaware of it):
#include <stdio.h>
int main()
{
unsigned char i = 0;
for (i = (unsigned char) 0; i <= (unsigned char) 255; i++)
{
printf("%d\n", i);
};
return 0;
}
Since i can take values between 0 and 255, I expected this look to print 1 to 255 and then quit but strangely it goes into an infinite loop. The for loops condition is never being met even though it prints 255. This is strange and I guess someone who is in computer science or engineering could probably figure this out.
So why is it an infinite loop? If it helps, its being run on a linux Pent 4 machine
thx for help
-
March 7th, 2011, 01:04 AM
#2
Re: anomalous loop behavior
You can use [ code ] tags to wrap around your code - '#' icon in rich edit mode.
The reason your code goes into an infinite loop is that the for loop exit condition is that i > 255 (since if i <= 255 , the loop continues).
If you take an integer type variable (char, int, long, unsigned char...) which contains its maximum value and add 1 to it - it will go back to its minimum value.
255 is the maximum possible value for unsigned char, so adding 1 to i when its value is 255, sets i to be 0, and hence your loop continues.
Regards,
Zachm
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|