Global vs Local Variables
Local Variables
So far, we’ve declared variables inside a function block—the indented portion of code that follows declaration of a function—which means they are local variables. Only the function declaring a local variable can see or modify it. Also, a local variable only exists while the function that declares it is using it. After that, it gets returned to unallocated memory so that another function (like loop) could use that memory for a different local variable.
Global Variables
If your program has to give more than one function access to a variable’s value, you can use global variables. To make a variable global, just declare it outside of any function. Then, all functions in the program will be able to modify or retrieve its value.
Example project: store_retrieve_global
The next example project declares a global variable called k, assigns a value to it, and then uses its value from within a function. In contrast, the variable called value is a local variable and only exists within the add_k function. If you try to show sting (value), you will only get a 0.
- Enter, name, and flash the project store_retrieve_global to your micro:bit.
Example: store_change_retrieve_global
If you want to permanently change the global variable from within the function, you must use the keyword global to call upon the global variable. In the project store_change_retrieve, k is created as a global variable with the value 5 assigned. Each time k is called upon in the function add_k it gets incremented by 1.
- Enter, name, and flash the project store_change_retrieve_global to your micro:bit.
- The display will first scroll 9, then 10. Do you understand why?