Skip to content

"static" keyword documentation example uses uninitialized variable #978

Open
@ryan-pebk

Description

@ryan-pebk

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions