Possible Duplicate:
Turbo C Array Question
#include <stdio.h>
#define LIM 40
int main()
{
int day=0;
float temp[LIM];
do
{
printf("Enter temperature for day %d.", day);
scanf("%f", &temp[day]);
}
while(temp[day++] && day<LIM );
}
About the last line. Why is it not satisfied with while(temp[day++] > 0)
? since I have set the LIM with the value of 40? Why should I add some additional condition, like day<LIM
?
Because, if you enter 41 numbers, you will write to a location outside the array, invoking the dreaded undefined behaviour. When you attempt to write to temp[40]
(the 41st element), you'll likely clobber memory that you shouldn't. It may work for a little bit beyond the end of the array but that's the nature of undefined behaviour. It's still not a good idea.
The day < LIM
bit will force the loop to exit when you've entered 40 temperatures, regardless of what value you've actually entered.