local-vs-nonlocal-variables

Search IconIcon to open search

Source: samek-embedded

Local variables are stored in the register , while non-local variables can be found in memory .

Local variable

1
2
3
4
5
int main()
{
	int counter = 0;
	...
}

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

1
2
3
4
5
int counter = 0; 
int main()
{
	...
}

Instruction set

LocalNon-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 address
      • LDR R0, [R0] (load to register) – loads the value located at the address
    • Storing to memory
      • LDR.N R1, memory – loads the memory address onto R1
      • STR R0, [R1] (store) – stores the value from register R0 into the memory at address [R1]