Minimised version below.
The original works as expected.
//Define an array of five folder sizes (number of tracks in each)
int folderSizes[] = {96, 106, 229, 159, 188}; //
void setup()
{
Serial.begin(115200);
delay(200); // Time to clear previous printing
Serial.println("Puzzle_Demo");
// Sum of the first three folders (96+106+229 = 431)
// Original successful code
int s = 0;
for (int i = 0; i < 3; i++)
{
s += folderSizes[i];
}
Serial.print("Result = ");
Serial.println(s);
} // End setup
void loop()
{
}
Then I used that identical code in a function instead. That failed with the error "'s' was not declared in this scope". I added an extra declaration which removed the error but the sketch gave a zero tresult.
//Define an array of five folder sizes (number of tracks in each)
int folderSizes[] = {96, 106, 229, 159, 188}; //
void setup()
{
Serial.begin(115200);
delay(200); // Time to clear previous printing
Serial.println("Puzzle_DemoFunctionFailed");
// Sum of the first three folders (96+106+229 = 431)
// Compiled but gave incorrect result (0 instead of 431)
int s = 0;
resultShouldBe();
Serial.print("Result = ");
Serial.println(s);
} // End setup
void loop()
{
}
int resultShouldBe()
{
int s = 0;
for (int i = 0; i < 4 ; i++)
{
s += folderSizes[i];
}
}
Throughout, I regarded the variable 's' as the result I was calculating and wanting to print.
The correct result was obtained by following the crucial advice from @red_car
//Define an array of five folder sizes (number of tracks in each)
int folderSizes[] = {96, 106, 229, 159, 188}; //
void setup()
{
Serial.begin(115200);
delay(200); // Time to clear previous printing.
Serial.println("Puzzle_DemoCorrect");
// Sum of the first three folders (96+106+229 = 431).
resultShouldBe();
Serial.print("Result = ");
Serial.println(resultShouldBe()); // Crucial edit
} // End setup
void loop()
{
}
int resultShouldBe()
{
int s = 0;
for (int i = 0; i < 4 ; i++)
{
s += folderSizes[i];
}
return s;
}
And following Paul's post #16
"return s; does not return the variable s. It returns the value in variable s. The variable s itself ceases to exist at the moment the function ends"
I now see the fundamental cause of my problem.
Must say that it doesn't square with my intuition though. Having 'returned' s it sort of goes against the grain that I can't use it directly elsewhere!
Valuable learning exercise, thanks to all.
P.S. Note that none of the other 560 lines of code would have helped resolve the issue.