reference-en icon indicating copy to clipboard operation
reference-en copied to clipboard

"static" keyword documentation example uses uninitialized variable

Open ryan-pebk opened this issue 1 year ago • 0 comments

On page https://www.arduino.cc/reference/en/language/variables/variable-scope-qualifiers/static/ the following example code is provided:

[code]int randomWalk(int moveSize) { static int place; // variable to store value in random walk - declared static so that it stores // values in between function calls, but no other functions can change its value

place = place + (random(-moveSize, moveSize + 1));

if (place < randomWalkLowRange) { // check lower and upper limits place = randomWalkLowRange + (randomWalkLowRange - place); // reflect number back in positive direction } else if (place > randomWalkHighRange) { place = randomWalkHighRange - (place - randomWalkHighRange); // reflect number back in negative direction }

return place; }[/code]

The first time randomWalk is called, place will not have been initialized, so the += will produce a runtime error. Perhaps the example should initialize it on declaration with a comment that explains the initializer is called only once?

It may be useful to include an additional comment about the initialization order of static variables in global scope as well - although perhaps this is "out of scope" for this documentation.

ryan-pebk avatar Mar 31 '24 00:03 ryan-pebk