Print 'Hello World' without using semicolon
June 12, 2012
Check if parenthesis are matched or not
June 12, 2012

Output of a C language Program

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

Your email address will not be published. Required fields are marked *