Find the mistake(s) in the following code

Find the mistake(s) in the following code:

unsigned int i;
for ( i = 100; i <= 0; --i)
	printf("%d\n", i);

My initial thoughts:
Because i is an unsigned integer, i cannot be negative. Hence the for loop should be:

for ( i = 100; i >= 0; --i)

Solution:
As i is unsigned integer, when i == 0 and one does –i, i will be FFFF FFFF in hex. Then when you do printf with “%d”, i will be interpret as an signed integer. Hence -1 will be printed. Then it will print all the way to the smallest integer, which is -2^{31}. A piece of perfectly working code should be:

unsigned int i;
for ( i = 100; i > 0; --i)
	printf("%u\n", i);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: