C - global variables and scope

A common task is to set a variable to a desired value, ideally in the setup() section of your code, and then in the loop() section you'd like to use that value in some way. For example like this:

Hmmm... a scope error in the loop() section, but not in the setup() section.



The reason this does not work is because, in C, variables declared in one subroutine are not accessible in other subroutines. In the code above, howManyLoops is a "local" variable. Because it's declared in setup() it only exists there, and its value and existence are unknown in any other subroutine!

The solution is to use a global variable: By declaring a variable outside (above) any subroutine, it will be available in all subroutines. This example compiled successfully:


For more information, google something like C variable scope.