I was trying something else but suddenly stuck with this infinite loop .
Please suggest an answer with explanation that what’s going on here in the below for loop
#include<stdio.h>
int main()
{
int x=0;
int i;
int array[5];
for(i=0;i<=5;i++)
{
array[i]=x;
printf("#%d value set in index %d\n",x,i);
}
return 0;
}
When I remove = sign in the condition of for loop It works fine.
But when I put this it goes to infinite loop , Why?
Accessing extra element (more than its limit) in array is undefined behaviour or what ?
Any help will appreciated.
Thanks in advance.
~
To avoid causing errors like this as easily, here’s two good rules for writing
forloops over actual (local) arrays:<, always. Never<=.sizeof array / sizeof *array. Note the asterisk in the second term.So, this loop should have been written:
and then you would have been safe.
Note that this only works for “real” arrays that have a size visible to
sizeof, if you’ve let the array “collapse” into a pointer it won’t work.Also note that
sizeofis not a function, so no()s are necessary around its argument in cases like these.