local-vs-nonlocal-variables
Source: samek-embedded
Local variables are stored in the register , while non-local variables can be found in memory .
Local variable
|
|
Note:
- All local variables on the stack go out of scope (get located outside of stack when the stack shrinks) when the function returns, so they can’t be accessed.
- Therefore, it is a bad idea to return a local variable.
- Make use of pointers instead.
- Alternatively, use the
static
keyword to tell the compuler to allocate memory to the variable outside of the stack.
Non-local variable
|
|
Instruction set
Local | Non-local |
---|---|
![]() | ![]() |
- More instructions as the CPU needs to load data from memory (in
RISC
architectures)
- Loading from memory
LDR.N R0, memory
(load to register from memory) – loads the memory addressLDR R0, [R0]
(load to register) – loads the value located at the address
- Storing to memory
LDR.N R1, memory
– loads the memory address onto R1STR R0, [R1]
(store) – stores the value from register R0 into the memory at address [R1]
- Loading from memory