Local Variable
Functions and procedures create new spaces within our code. These blocks of code are isolated from each other. This means that anything created within a function or procedure only exists while that function or procedure is running, much like we saw with the idea of scope within compound statements.
These are now several places where variables can be declared in your code. Variables declared within a function or procedure are called local variables, because they are local to function or procedure they are declared in. Moving forward, most of the variables in your code will be local variables.
As shown above, you can picture each procedure as containing a number of local variables. These variables are accessible within the procedure’s instructions. That is, the procedure’s block defines the scope where these variables are accessible. The same applies to functions.
Local Variables — when, why, and how
Whenever you need a function or procedure to remember something, you create a local variable to store that value. These variables exist only during the execution of the procedure or function, which is great as that means we never need to think about these variables when we are working elsewhere.
In C/C++
The syntax for declaring a local variable is the same as declaring any other kind of variable. The only difference is conceptual — any variable you declare within the statements of a function or procedure or function are local variables, and should be pictured as existing entirely within the function or procedure.
Examples
The following code creates a local variable called name
. This variable is declared within the say_hello
procedure, making it a local variable. Picture the say_hello
procedure as containing the name
variable, making the variable only accessible from the instructions within this procedure.
TODO: slider