Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

"static" keyword documentation example uses uninitialized variable #978

Open
ryan-pebk opened this issue Mar 31, 2024 · 0 comments
Open

Comments

@ryan-pebk
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant