Automatic variable: Difference between revisions

Content deleted Content added
Addbot (talk | contribs)
m Bot: Migrating 1 interwiki links, now provided by Wikidata on d:q1091711
Adding local short description: "Local variable in computer programming", overriding Wikidata description "stack-allocated variable that is automatically deallocated upon leaving the scope in which it was declared"
 
(43 intermediate revisions by 35 users not shown)
Line 1:
{{Short description|Local variable in computer programming}}
__NOTOC__
{{About|Automatic variables|the C++ keyword {{Cpp|auto}} used for [[type inference]]|C++11#Type inference}}
In [[computer programming]], an '''automatic variable''' is a [[scope (programming)|lexically-scoped]] [[Variable (programming)|variable]] which is allocated and deallocated automatically when program flow enters and leaves the variable's [[scope (programming)|scope]]. The term ''[[local variable]]'' is usually synonymous with automatic variable, since these are the same thing in many programming languages.
In [[computer programming]], an '''automatic variable''' is a local [[Variable (programming)|variable]] which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The [[Scope (computer science)|scope]] is the lexical context, particularly the function or block in which a variable is defined. Local data is typically (in most languages) invisible outside the function or lexical context where it is defined. Local data is also invisible and inaccessible to a ''called'' function,<ref group="note">unless it is a [[nested function]], which itself is ''defined'' along that local data</ref> but is not deallocated, coming back in scope as the [[execution thread]] returns to the caller.
 
Automatic local variables mayprimarily applies to [[Recursion (computer science)| recursive]] [[scope (programming)|lexically-scoped]] languages.<ref group="note">although they exist in a somewhat similar, but not identical, form also in recursive languages with [[dynamic scoping]], such as older variants of [[LISP]]</ref> Automatic local variables are benormally [[Stack-based memory allocation|allocated in the stack frame]] of the procedure in which they are declared;.<ref thisgroup="note">unless hasotherwise thespecified, usefulsuch effectas ofstatic allowingor [[recursion]]heap-based anddata, which are specifiable in some languages</ref> This was originally done to achieve [[reentrant (subroutine)|re-entrancy]]. (Forand efficiencyallowing [[recursion]],<ref group="note">When the reentrant property of the routine is used, for recursion or otherwise, the [[compiler optimization|optimizer]] willmust ''not'' try to allocate some of thesesuch variables in [[processor register]]s (for efficiency) as this would break the reentrancy.</ref> a consideration that still applies today. The concept of automatic variables in recursive (and [[nested function|nested]]) functions in a lexically scoped language was introduced to the wider audience with [[ALGOL]] in the late 1950s, and further popularized by its many descendants.
 
The term ''[[local variable]]'' is usually synonymous with automatic variable, since these are the same thing in many programming languages, but local is more general – most local variables are automatic local variables, but [[static local variable]]s also exist, notably in C. For a static local variable, the allocation is static (the lifetime is the entire program execution), not automatic, but it is only in scope during the execution of the function.
 
==In specific programming languages==
=== C, C++ ===
 
*{{See [[also|C syntax#Storage durationclass specifiers]]}}
 
=== C, C++ ===
(Called ''automatic'' variables.)
 
All variables declared within a [[block (programming)|block]] of code are automatic by default, but this can be made explicit with the <code>auto</code> keyword.<ref group="note">Note: the current C++ standard, [[C++11]], adds an additional meaning to the <code>auto</code> keyword, meaning a type that is [[Type inference|inferred]].</ref> An uninitialized automatic variable has an [[undefined behavior|undefined]] value until it is assigned a valid value of its type. <ref>{{As of|2008|alt=Current}} {{PDFlinkcite web|[url= http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf |title=C standard] }}&nbsp;{{small|(3.61&nbsp;[[Mebibyte|MiB]]<!-- application/pdf, 3788603 bytes -->)}}: section 6.2.4, Storage durations of objects</ref> The storage-class specifier <code>auto</code> can be added to these variable declarations as well, but as they are all automatic by default, this is entirely redundant and rarely done.
 
UsingIn C, using the storage class <code>register</code> instead of <code>auto</code> is a hint to the compiler to cache the variable in a processor register. Other than not allowing the referencingaddress-of operator (<code>&</code>) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.<ref>{{citation|url=https://en.cppreference.com/w/c/language/storage_duration| title=Storage Duration| website=cppreference.com}}</ref>
 
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., Seecalled [[RAIIResource Acquisition Is Initialization]] (RAII).
 
Since C++11, C++ allows variables to be declared with the <code>auto</code> type specifier,<ref>{{citation| url=http://en.cppreference.com/w/cpp/language/auto| title=Placeholder type specifiers| website=cppreference.com}}</ref> but this means that the variable's type is [[type inference|inferred]], and does not refer to the scope of the variable.
 
===Java===
(Called ''local variables''.)
 
Similar to C and C++, but there is no <code>auto</code> or <code>register</code> 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.<ref>{{cite web | url=http://java.sun.com/docs/books/jls/third_edition/html/typesValues.html#4.12.5 | title=4.12.5 Initial Values of Variables | publisher=Sun Microsystems | accessdateaccess-date=2008-10-17}}</ref> This differs from instance variables, which are implicitly initialized with default values (which are <tt>{{samp|0</tt>}} for numbers and <tt>{{samp|null</tt>}} for objects).
 
===Perl===
(Called ''lexical'', ''my'' or ''private'' variables.)
 
In Perl, local variables are declared using the <code>my</code> operator. Uninitialized scalars will have the value <code>undef</code>; uninitialized arrays or hashes will be <code>()</code>.<ref>{{cite web | url=http://perldoc.perl.org/perlsub.html#Private-Variables-via-my() | title=Private variables via my() - perlsub - perldoc.perl.org | publisher= | accessdateaccess-date=2008-10-17}}</ref>
 
Perl also has a <code>[[Local variable|local]]</code> operator that does not create automatic variables,<ref>{{cite web | url=http://perldoc.perl.org/perlsub.html#Temporary-Values-via-local%28%29 | title=Temporary values via local() - perlsub - perldoc.perl.org | publisher= | accessdateaccess-date=2011-02-25}}</ref> instead giving global (package) variables a temporary value, which is [[Scope_(computer_science)#Dynamic_scoping|dynamically scoped]] to the enclosing block. When the scope of the variable is left, the old value is restored.
 
==See also==
*[[C syntax#Storage class specifiers]]
 
* [[Variable-length array]] ([[C99]] new feature)
* [[C syntax#Storage duration specifiers]]
*[[Call stack]]
* [[Variable-length array]] ([[C99]] new feature)
*[[Object lifetime]]
 
==Notes==
{{reflistReflist|group=note}}
 
==References==
{{Reflist}}
<references />
 
{{DEFAULTSORT:Automatic Variable}}
{{Memory management}}
[[Category:Memory management]]
[[Category:Variable (computer programmingscience)]]
 
[[es:Asignación automática de memoria]]
[[de:Automatische Variable]]