Share to: share facebook share twitter share wa share telegram print page

Automatic variable

In computer programming, an automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope. The 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,[note 1] but is not deallocated, coming back in scope as the execution thread returns to the caller.

Automatic local variables primarily applies to recursive lexically-scoped languages.[note 2] Automatic local variables are normally allocated in the stack frame of the procedure in which they are declared.[note 3] This was originally done to achieve re-entrancy and allowing recursion,[note 4] a consideration that still applies today. The concept of automatic variables in recursive (and 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 variables 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++

(Called automatic variables.)

All variables declared within a block of code are automatic by default. An uninitialized automatic variable has an undefined value until it is assigned a valid value of its type. [1] The storage-class specifier auto can be added to these variable declarations as well, but as they are all automatic by default this is entirely redundant and rarely done.

In C, using the storage class register is a hint to the compiler to cache the variable in a processor register. Other than not allowing the address-of operator (&) to be used on the variable or any of its subcomponents, the compiler is free to ignore the hint.[2]

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 Resource Acquisition Is Initialization (RAII).

Since C++11, C++ allows variables to be declared with the auto type specifier,[3] but this means that the variable's type is inferred, and does not refer to the scope of the variable.

Java

(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.[4] This differs from instance variables, which are implicitly initialized with default values (which are 0 for numbers and null for objects).

Perl

(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 ().[5]

Perl also has a local operator that does not create automatic variables,[6] 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.

See also

Notes

  1. ^ unless it is a nested function, which itself is defined along that local data
  2. ^ although they exist in a somewhat similar, but not identical, form also in recursive languages with dynamic scoping, such as older variants of LISP
  3. ^ unless otherwise specified, such as static or heap-based data, which are specifiable in some languages
  4. ^ When the reentrant property of the routine is used, for recursion or otherwise, the optimizer must not try to allocate such variables in processor registers (for efficiency) as this would break the reentrancy.

References

  1. ^ Current "C standard" (PDF). (3.61 MiB): section 6.2.4, Storage durations of objects
  2. ^ "Storage Duration", cppreference.com
  3. ^ "Placeholder type specifiers", cppreference.com
  4. ^ "4.12.5 Initial Values of Variables". Sun Microsystems. Retrieved 2008-10-17.
  5. ^ "Private variables via my() - perlsub - perldoc.perl.org". Retrieved 2008-10-17.
  6. ^ "Temporary values via local() - perlsub - perldoc.perl.org". Retrieved 2011-02-25.


Read other articles:

This article is an orphan, as no other articles link to it. Please introduce links to this page from related articles; try the Find link tool for suggestions. (June 2016) A corner of the Drum Museum featured at the Ten Drum Culture Village, showcasing different kinds of drums from East Asian countries. Located in the Rende District of Tainan, Taiwan,[1] Ten Drum Rende Creative Park was once a busy sugar mill but had been left disused for years. After being taken over by the local drum...

Glacier in Graham Land, Antarctica Location of Oscar II Coast on Antarctic Peninsula. Hektoria Glacier (65°3′S 61°31′W / 65.050°S 61.517°W / -65.050; -61.517) is a glacier flowing south from the area around Mount Johnston between Mount Quandary and Zagreus Ridge into Vaughan Inlet next west of Brenitsa Glacier and east of Green Glacier, on the east coast of the Antarctic Peninsula. The name Hektoria Fiords was given by Sir Hubert Wilkins during his flight of 20...

شلوسك فروتسلاو تأسس عام 1947  الملعب ملعب مييسكي  البلد بولندا  الدوري الدوري البولندي الممتاز  المدرب تاديوز بافووفسكي (19 فبراير 2018–ديسمبر 2018)جاسيك ماجييرا (21 أبريل 2023–)  الموقع الرسمي الموقع الرسمي  تعديل مصدري - تعديل   ملعب مييسكي (فروتسواف) نادي شلوسك ف...

De Mysteriis Dom SathanasÁlbum de estudio de MayhemPublicación 24 de mayo de 1994Grabación 1992-1993 en la sala Grieg, Bergen, NoruegaGénero(s) Black metalDuración 46:01Discográfica Deathlike SilenceProductor(es) Pytten, Euronymous, Hellhamer Cronología de Mayhem De Mysteriis Dom Sathanas (1994) Grand Declaration of War (2000) [editar datos en Wikidata] De Mysteriis Dom Sathanas es el primer álbum de estudio de la banda noruega de black metal Mayhem, publicado el 24 de mayo ...

List of states in the Holy Roman Empire A B C D E F G H I J K L M N O P Q R S T U V W Z Free Imperial CitiesImperial abbeysImperial KnightsImperial Villages This is a list of states in the Holy Roman Empire beginning with the letter G: Name Type Circle Bench Formed Notes Gandersheim Abbacy Upp Sax RP 856 919: Imperial immediacy1206: HRE Princess1802: To Brunswick-Wolfenbüttel1807: To Westphalia1815: To Brunswick GdańskSee: Danzig Imperial City Gelnhausen Imperial Free City Upp Rhen RH 1170 ...

Robert Kaliňák Robert Kaliňák (* 11. Mai 1971 in Bratislava) ist ein slowakischer Politiker (Smer) und mehrmaliger Innenminister (2006–2010, 2012–2018). Inhaltsverzeichnis 1 Leben 2 Verwicklung in den Entführungsfall Trịnh Xuân Thanh 3 Politische Positionen 4 Weblinks 5 Fußnoten Leben Kaliňák studierte an der Juristischen Fakultät der Comenius-Universität Bratislava. Bis 2002 arbeitete er als Rechtsanwalt. Er ist Mitglied der SMER. Bei den Parlamentswahlen 2006, 2010 und 2012...

Donald Ervin KnuthDonald Knuth at a reception for the Open Content Alliance, October 25, 2005Lahir10 Januari 1938 (umur 85)Milwaukee, Wisconsin, U.S.Tempat tinggalU.S.KebangsaanAmericanAlmamaterCase Institute of TechnologyCalifornia Institute of TechnologyDikenal atasThe Art of Computer ProgrammingTeX, METAFONTKnuth–Morris–Pratt algorithmKnuth–Bendix completion algorithmMMIXPenghargaanJohn von Neumann Medal (1995) Turing Award (1974) Kyoto Prize (1996)Karier ilmiahBidangComputer sc...

American TV series or program Step It Up and DanceGenreRealityCountry of originUnited StatesOriginal languageEnglishNo. of seasons1No. of episodes10ProductionRunning time44 minutesOriginal releaseNetworkBravoReleaseApril 3 (2008-04-03) –June 8, 2008 (2008-06-08) Step It Up and Dance is an American reality television competition series where contestants are supposed to learn what it takes to make it big in the cutthroat dance industry. Actress and dancer Elizabeth Berkley...

Spanish footballer For another person with the same nickname, see Juanfran. In this Spanish name, the first or paternal surname is Torres and the second or maternal family name is Belén. Juanfran Juanfran with Atlético Madrid in 2018Personal informationFull name Juan Francisco Torres Belén[1]Date of birth (1985-01-09) 9 January 1985 (age 38)Place of birth Crevillent, SpainHeight 1.81 m (5 ft 11 in)[2]Position(s) Right-backYouth career Kelme Real ...

Abou Mohammed al-Adnani Nom de naissance Taha Sobhi Falaha Naissance 1977Binnish (Syrie) Décès 30 août 2016 (à 39 ans)Al-Bab (Syrie)Mort au combat Origine Syrien Allégeance Jama'at al-Tawhid wal-Jihad (2003) Al-Qaïda en Irak(2004-2005) État islamique d'Irak(2010-2013) État islamique en Irak et au Levant(2013-2014) État islamique(2014-2016) Grade Émir Conflits Guerre d'IrakGuerre civile syrienneSeconde guerre civile irakienne modifier  Taha Sobhi Falaha (en arabe :

For other uses, see Angriff (disambiguation). Masthead of Der Angriff from 30 January 1933 (Machtergreifung of Adolf Hitler) Der Angriff (in English The Attack) was the official newspaper of the Berlin Gau of the Nazi Party. Founded in 1927, the last edition of the newspaper was published on 24 April 1945. History The newspaper was set up by Joseph Goebbels, who in 1926 had become the Nazi Party leader (Gauleiter) in Berlin, and the party provided most of the money needed to ensure publicatio...

Australia14º lugar Oficial Alternativo Asociación Federación de Fútbol de Australia Confederación OFC Participación 1a Entrenador Ralé Rašić La Selección de Australia fue uno de los 16 países participantes que disputó la Copa Mundial de Fútbol de 1974, que se realizó en Alemania. Clasificación Artículo principal: Clasificación de AFC y OFC para la Copa Mundial de Fútbol de 1974 Para clasificar al Mundial, Australia comenzó su camino en la eliminatoria conjunta con Asia...

Japanese company Seiko Instruments Inc.Headquarters in ChibaNative nameセイコーインスツル株式会社Romanized nameSeikō Insutsuru Kabushiki-gaishaTypeSubsidiaryIndustryElectronicsFounded1937; 86 years ago (1937)Tokyo, JapanHeadquartersChiba, Chiba, JapanKey peopleYoshinobu Nakamura, ChairmanTetsu Kobayashi, PresidentProductsMicromechatronics devices, Network components, Information-related equipment and services, Printers, Scientific instruments, etc.Revenue ¥51,...

東北大學未來科學技術共同研究中心川島隆太教授監修 大人的DS腦力鍛鍊東北大学未来科学技術共同研究センター 川島隆太教授監修 脳を鍛える大人のDSトレーニングBrain Age: Train Your Brain in Minutes a Day!Dr. Kawashima's Brain Training: How Old Is Your Brain?日文版游戏封面类型益智遊戲平台任天堂DSVirtual Console(Wii U)开发商任天堂企划开发本部发行商任天堂总监河本浩一音乐Akito Nakatsuka...

Over 80 species of ants can be found in Sweden, distributed across 21 genera belonging to four subfamilies. Genera Dolichoderinae Linepithema Tapinoma Technomyrmex Formicinae Camponotus Formica Lasius Paratrechina Polyergus Myrmicinae Anergates Formicoxenus Harpagoxenus Leptothorax Monomorium Myrmecina Myrmica Solenopsis Stenamma Temnothorax Tetramorium Strongylognathus Ponerinae Hypoponera Species Subfamily Species Swedish name Conservation status[a] Image Ref Dolichoderinae Linepith...

Riot Games, Inc Тип дочерняя компания Основание 2006 Прежние названия Etech Studio Основатели Брэндон Бек Марк Мэррилл Расположение  США: Лос-Анджелес (Калифорния) Отрасль разработка программного обеспечения (МСОК: 6201) Продукция компьютерные игры Число сотрудников 5500 (2022) Подр...

Japanese rock band This article needs additional citations for verification. Please help improve this article by adding citations to reliable sources. Unsourced material may be challenged and removed.Find sources: Polysics – news · newspapers · books · scholar · JSTOR (September 2020) (Learn how and when to remove this template message) PolysicsPolysics live in France 2008Background informationOriginTokyo, JapanGenres New wave synthpop art pop electrop...

Pour les articles homonymes, voir Snow. Cet article est une ébauche concernant un cours d’eau et l’Alaska. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. SnowLocalisationPays  États-UnisLocalisation Alaska, borough de la péninsule de KenaiCoordonnées 60° 20′ 18″ N, 149° 21′ 14″ ODimensionsLongueur 45 kmHydrographieType Cours d'eau (en)Affluent South Fork Snow ...

Chinese professional League of Legends player In this Chinese name, the family name is Jian. UziJian in 2022Current teamTeamEdward GamingRoleBot LanerGameLeague of LegendsLeagueLPLPersonal informationName简自豪(Jian Zihao)Born (1997-03-29) March 29, 1997 (age 26)[1]Yichang, Hubei, China[2]NationalityChineseCareer informationPlaying career2012–presentRoleBot LanerTeam history2012–2014Royal Club2014Star Horn Royal Club2014–2015OMG2015–2016Qiao Gu2016Newbee2016–...

Israeli politician Eliezer PeriFaction represented in the Knesset1949–1955Mapam Personal detailsBorn2 February 1902Surochów, Austria-HungaryDied1 December 1970 (aged 68) Eliezer Peri (Hebrew: אליעזר פרי) born Eliezer Wilder-Frei; 2 February 1902 – 1 December 1970, was an Israeli politician who served as a member of the Knesset for Mapam between 1949 and 1955. Biography Born in the village of Surochów, near Jarosław, in the Kingdom of Galicia (today in Poland), Peri helped ...

Kembali kehalaman sebelumnya