-1

I am learning programming on my own. I came across arrays and tried to alter the for loop's condition from i < 5 to i <=5 , the outcome was unexpected, infinite loop:

#include <stdio.h>

int main(void)
{
    int a[5] , i , j = 0;
    for (i=0;i<=5;i++)
    {
        a[i] = 2;
        printf("%d " , a[5]);
    }
    return 0;
}

Again I tried the same but this time with a variable , but this time no infinite loop.

#include <stdio.h>

int main(void)
{
    int a[5] , i , j = 0;
    for (i=0;i<=5;i++)
    {
        a[i] = j;
        printf("%d " , a[5]);
    }
    return 0;
}

Please explain to me why the loop was infinite in first and not in second case.

Shafik Yaghmour
  • 154,301
  • 39
  • 440
  • 740
jksprt0
  • 13
  • 2
  • 3
    You need to include the code in your question, not a screenshot. From a quick glance this looks very similar to [this question](http://stackoverflow.com/q/32506643/1708801), so it is probably aggressive optimization around undefined behavior since you are going out of bounds on the last array access. – Shafik Yaghmour Sep 23 '15 at 12:45
  • 4
    You are going over the array and most likely writing on top of the `i` variable. Undefined behaviour, don't do that. Also don't post code as screenshots. – Sami Kuhmonen Sep 23 '15 at 12:45
  • Once you add the code to your question I am happy to vote reopen but it will probably be closed again as a duplicate though if I am correct about my comment above. – Shafik Yaghmour Sep 23 '15 at 13:12
  • i apologise its my first time asking question here , i wanted to show the output too that's why posted screenshots . I am sorry – jksprt0 Sep 23 '15 at 15:41
  • Voting to reopen, it look very similar to the question I link above but I can not reproduce. Can you explain which compiler and what flags you are using? – Shafik Yaghmour Sep 23 '15 at 18:43

1 Answers1

3

You declared your array to be size 5. Thus valid indexes are 0 to 4 (inclusive). In the last pass of the loop, you write to location a[5], which clobbers whatever variable happens to live at that address right after the end of the array. That might your loop variable i, depending on how the compiler lays the variables out in memory. The result is generally unpredictable.

Hellmar Becker
  • 2,824
  • 12
  • 18