In computer programming, an automatic variable is a lexically-scoped variable which is allocated and de-allocated automatically when program flow enters and leaves the variable's scope. The term local variable is usually synonymous with automatic variable, since these are the same thing in many programming languages.
Automatic variables may be allocated in the stack frame of the procedure in which they are declared; this has the useful effect of allowing recursion and re-entrancy. (For efficiency, the optimizer will try to allocate some of these variables in processor registers.)
(Called automatic variables.)
All variables declared within a block of code are automatic by default, but this can be made explicit with the auto
keyword.[1] An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type.[2]
Using the storage class register
instead of auto
is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencing operator (&
) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.
In C++ the constructor of automatic variables is called when the execution reaches the place of declaration. The destructor is called when it reaches the end of the given program block (program blocks are surrounded by curly brackets). This feature is often used to manage resource allocation and deallocation, like opening and then automatically closing files or freeing up memory. See RAII.
(Called local variables.)
Similar to C and C++, but there is no auto
or register
keyword. However, the Java compiler will not allow the usage of a not-explicitly-initialized local variable and will give a compilation error (unlike C and C++ where the compiler will usually only give a warning). The Java standard demands that every local variable must be explicitly initialized before being used.[3] This differs from instance variables, which are implicitly initialized with default values (which are 0 for numbers and null for objects).
(Called lexical, my or private variables.)
In Perl, local variables are declared using the my
operator. Uninitialized scalars will have the value undef
; uninitialized arrays or hashes will be ()
.[4]
Perl also has a local
operator that does not create automatic variables,[5] instead giving global (package) variables a temporary value, which is dynamically scoped to the enclosing block. When the scope of the variable is left, the old value is restored.
auto
keyword, meaning a type that is inferred.