Tuesday, April 1, 2014

Find the mistake(s) in the code

Problem
Find the mistake(s) in the following code:
unsigned int i;
for ( i = 100; i <= 0; --i)
    printf("%d\n", i);

Solution

Because i is an unsigned integer, i cannot be negative. Hence the for loop should be:
for ( i = 100; i >= 0; --i)

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);



0 comments:

Post a Comment