Why are there so many global variables in the examples?

Even in the field of safety-critical software, there is argument over whether variables should always be declared a locally as possible. I'm of the opinion that they should be, for the following reasons:

  1. If you declare a variable in the smallest enclosing scope in which it is used, then the program is clearer to read: you know that the variable has no meaning outside that scope, can't be directly modified outside that scope, and should be initialized within that scope before it is used. This applies not only when the program is worked on by multiple developers, but also to you when you come back to the program a year after you wrote it.

  2. Similarly, the compiler or static analysis tool can warn if the variable is not "definitely initialized' (in Java parlance). [However, the Arduino IDE runs the compiler at a low warning level so that it doesn't give these warnings.]

  3. The compiler can often generate better code when variables are declared in the smallest enclosing scope, e.g. it can avoid storing the value of a nonstatic variable that is about to pass out of scope, or even keep the variable in a register all the time. So the code tends to be faster and smaller. There is an exception that has already been noted, which is that non-global initialized static variables of non-primitive types have their initialization deferred until they are first 'executed', which means the code has to maintain and check a flag.

  4. A global variable always occupies memory, but a local nonstatic variable only occupies memory when the function or block (depending on compiler) containing it is being executed.