Search code examples
carraysfor-loopconditional-statementsgarbage

In C programming, what is the difference between for(int i=0; st[i]; i++) and for(int i=0; i<st[length of the array];i++)


In the below program, while using st[i] on the for loop condition :

#include<stdio.h> 
int main() 
{ 
     int st[] ={1,2,3,4,5,6,7,8}; 
     int i; 
     for(i=0; st[i]; i++) 
         printf("\n%d %d %d %d", str[i], *(str+i), *(i+str), i[str]); 
     return 0;
}   

Output:

1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8
-874149648 -874149648 -874149648 -874149648
32764 32764 32764 32764

In the below program, while using i<8 on the for loop condition:

#include<stdio.h> 
int main() 
{ 
     int str[8] ={1,2,3,4,5,6,7,8}; 
     int i; 
     for(i=0; i<8; i++) 
         printf("\n%d %d %d %d", str[i], *(str+i), *(i+str), i[str]); 
     return 0;
}  

Output: input

1 1 1 1
2 2 2 2
3 3 3 3
4 4 4 4
5 5 5 5
6 6 6 6
7 7 7 7
8 8 8 8

Can anyone please explain what is happening over there in st[i]. If it is garbage value means why it stops after printing that two extra iteration.

Compiler: onlinegdb.com -c compiler


Solution

  • A for loop will continue as long as the middle expression evaluates to true, i.e. a non-zero value. So in this case:

    for(i=0; st[i]; i++) 
    

    The loop continues as long as st[i] is not 0. Since there are no elements of the array that contain 0, this ends up reading past the end of the array. Doing so invokes undefined behavior, which in this case manifests as an indeterminate number of seemingly random values being printed.