You do initialize before loop because you should not assume that your defined variable will always be known inside and outside of the loop.
In below example without initialization before the loop it will be returned Error 29 if BarCount
is less than 10002 (i
less than 10001). So cAvg
will become unknown to cs += Nz(cAvg[i]);
line within the loop and to Plot
() line outside of loop.
// No initialization of cAvg variable before loop
cs = 0;
for (i = 0; i < BarCount; i++) { // Run loop from 0 to BarCount-1
if ( i > 10000 ) { // if bar index greater than 10000
cAvg[i] = (High[i] + Low[i]) / 2; // Calculate average at each bar
} // end of if
cs += Nz(cAvg[i]); // cAvg unknown in case of if statement being false
// resulting in Error 29 -> variable used without being initialized
}
Plot( cAvg, "Price", colorRed );// results in Error 29 outside of loop in case of if statement being false
But also this one will return Error if Barcount is less than 11:
for (i = 10; i < BarCount; i++) { // Run loop from 10 to BarCount-1
cAvg[i] = (High[i] + Low[i]) / 2; // Calculate average at each bar
}
// Will result in Error 29 for Plot() line
// if BarCount is less than 11 and cAvg not initialized before loop
Plot( cAvg, "Price", colorRed );
In addition: important read about not making assumptions on number of bars
As for NULL.. NULL is not equal to zero. NULL ( -1e10
) in AFL means Nothing/Empty..
What you assign to a variable depends of what you need at the end.
If you sum up like in below example (see cs +=
) then you initialize result variable to zero before (in most cases) but not to NULL. Otherwise cs
in example below would return Null
in the end too. And we use Nz() function there since cAvg
may become NULL. So without Nz() cs
would become NULL too then. But summing together with Nz() -> Null cases will be converted to zero (valueifnull of Nz() is set to zero by default).
cs = 0;
cAvg = NULL;
for (i = 0; i < BarCount; i++) { // Run loop from 0 to BarCount-1
cAvg[i] = (High[i] + Low[i]) / 2; // Calculate average at each bar
if ( i > 20 AND i < 30 )
cAvg[i] = Null;
cs += Nz(cAvg[i]); // sum up cAvg
}
printf( "%g", cs ); // cs is number not array
Plot( cAvg, "Price", colorRed );
Please before posting read this important thread and please take careful look at GIF animation in first post there.
Next if you post code not being yours you should add link to its original presentation. It is taken from here - "Coding your own custom stop types" section there.
Now what is it about and what is that code doing... well, following might help to understand better.
Note: also in above code we initialize variable before loop as it may be unknown otherwise.