Why I am getting this output?output = 012345

Viewed 69
#include<stdio.h> 
#include<conio.h> 

void main()
{
    int i;                         
    for ( ;i<=5;i++)
    {
        printf ("%d",i);
    }
}

Why I am getting this output? output = 012345

  1. I did not expecting any output. because as i didnt intilise i, so from where he is going to start?

  2. if i will be intilise by a undefined value, why I am getting the same output as many times i run the code?

1 Answers
  • int i;
    

    i is uninitialized and holds an indeterminate value. 0 is one of the many values it can contain.

  • for ( ;i<=5;i++)
    

    In both i<=5 and i++ you read i that has an indeterminate value. The compiler is allowed to assume that you never do that and may produce assembler code that does anything. The program therefore has what is called undefined behavior.

  • printf ("%d",i);
    

    Here you print i whatever it may be. If i happened to contain 0 when you left it uninitialized - and if the compiler was "kind" enough to let your failure to initialize i through without producing an executable that crashes (or worse), then the loop will step i from 0 to 6. When it reaches 6, the condition, i<=5, will be false and the loop will end. Only for the values when i is less than, or equal to, 5 will printf ("%d",i); be reached.

Note that the program may do different things when you run it multiple times because it has undefined behavior. i may suddenly be -98723849 when you run the program and then your loop will print the values from -98723849 up to 5.

I did not expecting any output. because as i didnt intilise i, so from where he is going to start?

As mentioned - the program could do just about anything because you didn't initialize i and then read from it. In your case, it seems i contained a 0 and that the program appears to behave as-if you initialized it to 0. Again, this is "pure luck" - no matter how many times in a row it displays the same behavior.

if i will be intilise by a undefined value, why I am getting the same output as many times i run the code?

Because the program has undefined behavior. It may repeat the same thing over and over again for many years. It's a ticking bomb that may suddenly explode one day.

Related