arduino / reference-en

Editable source for the Arduino Reference
https://www.arduino.cc/reference/en/
Other
165 stars 732 forks source link

"static" keyword documentation example uses uninitialized variable #978

Open ryan-pebk opened 7 months ago

ryan-pebk commented 7 months ago

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.