arduino / arduino/reference-en

"static" keyword documentation example uses uninitialized variable

Open
#978 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
No language data
Stars
173
Forks
704
PR merge metrics
No merged PRs in 30d

Description

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.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start at the linked static keyword reference page and inspect the example code shown in the issue. Update the example so place has an initializer and explain that static local initialization occurs only once; the documentation is done when the example no longer uses an uninitialized value and the scope-related explanation remains accurate.

Written by the indexing model from the issue text.

Assessment

Tech stack
arduino
Domain
documentation
Issue type
Documentation
Difficulty
1/5
Estimated time
Under an hour
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.