Recently I tried coding a particular problem in codechef like this…
while(t--) // t indicating the number of test cases
{
int array1[1001];
int array2[1001];
//rest of code
}
What I noticed is that the array elements where not set to their default values after each iteration.So the previous values assigned to the array elements were retained.So does this mean that the declaration happens only the first time the loop is executed? And then the successive iterations use the same reference?
If you do the same, like this i.e. declaring the arrays inside the while loop containing test cases, then each time (with each test case) previous values will not be retained.
What you can do?
Declare these arrays globally (by default all values are zero) and memset() for each array in the while loop.
Local variables are not initialized. In runtime some memory is used and you do not know the data in memory, you have to clear the memory first by memset() of for loop…
@betlista : The one without initializing will contain garbage values. But I don’t think, the values updated once in the while loop should be carried forward to the next iteration. "...is that the array elements were not set to their default values after each iteration. So the previous values assigned to the array elements were retained. So does this mean that the declaration happens only the first time the loop is executed?" So if the array elements are assigned to some values (during some operation in the while loop), will they retain in the next iteration?
you are declaring the array inside of while loop. So for every iteration array will redeclare.
soultion is keep array declaration outof loop or use static.
@bugkiller Yes ,they do get retained…try testing by printing the array elements for each iteration …after doing something to the array in each iteration…
Brother Keep array declaration outside the for loop. Its very bad programming practice, because every time the loop runs the new arrays are re-initialized.
Brother Keep array declaration outside the for loop. Its very bad programming practice, because every time the loop runs the new arrays are re-initialized.