Jun 122012
 
 C Tags:  Add comments

What will be the output of the below code in C language:

int main ()
 { 
     unsigned int cnt;

     for (cnt = 5; cnt >= 0; cnt--)
         printf("%d ", cnt);
 }

Solution:

No, the answer is NOT 5 4 3 2 1 0.

We are printing the value of cnt till its non-negative (Till it becomes negative). cnt is an unsigned int, no matter what, its value is always positive. Hence the loop is Infinite 🙂

What exactly will be printed is implementation dependent, because when cnt is decremented to hold a negative value (or an unsigned int is assigned a negative value like -1), the result is undefined.

The loop will not terminate gracefully.

Hence, the result is undefined (after 5 4 3 2 1 0 ), but expect a lot of values getting printed before your program crash with a core dump.

 Leave a Reply

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

(required)

(required)