The following article is part of a series of posts I made on a Discord server.
Original publication date: 2024-09-27
— Previous: Variable Scope (Part 1 of 3)
Variable Scope (Part 2 of 3)
Examples
Variable accessibility depending on the relationship between blocks
(image-1) Global variables can be accessed from any part of the program; there isn’t much to consider here.
image-1

Now, for local variables:
Inside
FunctionC, there is a request to access (or modify)VariableA. This variable was created withinFunctionA, andFunctionCis also nested withinFunctionA. By the way, every child block dies before its parent block. Based on this,VariableAis alive and accessible throughout the entire lifetime ofFunctionC, provided thatVariableAwas created beforeFunctionC.In
FunctionB, access toVariableCis requested, but this variable only exists during the lifetime ofFunctionD. If the request is made beforeFunctionD, thenVariableChasn’t been created yet; if it is made afterFunctionD, then it is already dead. Basically, the parent block cannot access the variables of the child block.Finally, inside
FunctionD, a request is made forVariableB, which lives inFunctionA. However,FunctionDis a “nephew” ofFunctionAand they do not exist at the same time.
Sibling blocks do not live at the same time; one sibling block lives and dies before or after another. (We break this statement with parallelism and concurrency, but now is not the time to get into that).
(image-2) In this presentation, it is easier to observe the accessibility of variables depending on the block relationship.
image-2

Child blocks are directly above their parent block.
Sibling blocks are located at the same level.
Additionally, the lifetimes of the blocks can be represented on the horizontal axis and do not overlap.
The arrows indicate the direction of the request for a variable, and just like in image-1, variables outside their own block only continue to live if they belong to the parent block and/or direct ancestry.
— Downloads
Excalidraw File— End of section
— Next: Variable Scope (Part 3 of 3)
