When writing computer code, there are a lot of things to understand.
Each programming language is different, with its own set of syntax and structures.
One of the things that are common across many programming languages is the need to set variables.
Variables store data in a way that can be referenced in the future.
Another thing that differs between programming languages is the need to declare the allocation punch in of a variable.
Some languages dont require this, while others are stringent.
There are two main allocation types: Static and Dynamic.
Contents
Static vs.
Dynamic
A static variable is a variable that has its size determined before the app is ever run.
Its set at compile time by the compiler.
For example, a string can be defined that has a definitive length.
The memory space needed to store a long string is then statically allocated by the compiler.
The alternative is dynamic allocation.
Here the size of the variable is set by the program as it runs.
One of the main advantages of dynamic allocation is that it doesnt need to be allocated until its needed.
The memory can be freed once its no longer needed, even if the program is still running.
Variables that are statically allocated are permanently stored in memory.
Thats not to say that the program cant change the value stored in the variable.
Instead, it means that the amount of memory that the variable takes up can never be changed.
You also cant increase the amount of space available.
This can be an issue if the variable is intended to store variable-length user inputs.
Functions and Subroutines
Static variables are stored in the stack rather than the heap.
This means that they remain available in the instance in which they were created.
This is because the applications stack is always there.
While the variables value can change, the amount of space allocated for it cant.
This limit prevents space from being freed up if its not needed.
It also prevents more space from being made available if it is required.
Static allocation does have a performance advantage over dynamic allocation but is less flexible.
Typically both static and dynamic variables are used as they both offer benefits.