3. Stack, local variables and static locals
09/02/23
Stack
- Stack is LIFO
- Function calls (Stack frames) are store on a stack in memory
- Most stacks go down in memory address
- Values are stored together in the stack frame
Lifetime of a local variables
- Local variables exist for the duration of the stack frame they are in
- They get destroyed; if you use
malloc()
you need to callfree()
⚠️DANGER⚠️
- Your local variables only exist for as long as the block in which they are defined.
- Do not access them after that
- Do not assume that they keep their value after the function ends
Global and static local variables
Global Variables
- Variables are declared outside of all functions and last for the duration of the program
- All functions in the file can access goals
- Can be hidden from other files
Local Variables
- Can be
static
- Means not moving/unchanging
- NOT the same as static member variables
- NOT the same as
const
- Static local variables remember their value between function calls