Static (keyword)


static is a reserved word in many programming languages to modify a declaration. The effect of the keyword varies depending on the details of the specific programming language, most commonly used to modify the lifetime (as a static variable) and visibility (depending on linkage), or to specify a class member instead of an instance member in classes.

Origin

In the predecessors of C, including BCPL and B, there was already a concept of static storage.,[1][2] which meant a storage which is always in existence. However, In B, there wasn't a static keyword, but there was an extrn keyword to specify external storage (external to all functions and must be defined outside a function), which is always static, in contrast with auto keyword, which declared an variable with auto storage - one appears whenever the function is invoked, and disappears when the function is left.[2] All variables must be declared, as one of auto, extrn, or implicitly as function arguments.

C was developed as a successor of B, and the static and register keyword were added as storage class specifiers, alongside with auto and extern, which kept their meaning from B. However, in C, the concept of linkage for variables outside functions was introduced. A C program can be formed by multiple compilation units and linked together to form a complete program, which a variable or a function can be either specified as having internal linkage (visible to its own compilation unit only), or external linkage (visible to the whole program). These keywords specify both the storage duration and linkage as follows:[3]

Storage class Duration Linkage
extern static (program execution) external (whole program)
static static (program execution) internal (translation unit only) for top-level identifier
none for block-scope variables
auto, register function execution none

Every variable and function has one of these storage classes; if a declaration does not specify the storage class, a context-dependent default is used:

  • extern for all top-level declarations in a source file,
  • auto for variables declared in function bodies.

So, in C, although the static keyword, when used on variables, always declare a variable with static storage duration, there are two distinct meanings of the keyword, depending on where it is used:

  • Top-level declaration: to declare an identifier with internal instead of external linkage, applicable to both variables and functions.
  • Block-scoped declaration: to declare a variable with static instead of automatic storage duration. C doesn't support block-scoped functions.

Therefore, in C, the term "static variable" has two meanings which are easy to confuse:

  1. A variable with the same lifetime as the program, as described above (language-independent); or
  2. (C-family-specific) A variable declared with storage class static.

Variables with storage class extern, which include variables declared at top level without an explicit storage class, are static in the first meaning but not the second.

In C++ (not C), the static keyword can also be used to declare a member variable in a class to have static storage duration as well, independent from the storage duration of the class object itself, and such a variable must be defined outside the class. The effect is that the variable is shared among all class instances, becoming a class member instead of an instance member. When applied to a member function (method), it specifies that the member function operates independently of an instance, which means it can't access any non-static members of the class nor the this pointer.

As a storage duration specifier

The static keyword is used in many programming languages to specify a local variable to have a lifetime of the whole program, preserved between function invocations, instead of having its own copy for each function invocation as in automatic storage duration, inherited from the usage in C.

Examples of programming languages which support the usage of static keyword for local variables to be kept across invocation include such as C, C++, Objective-C, C#, PHP.

The following programming languages with C-like syntax do not support static local variables as in C: Java, JavaScript, Dart. In these languages, a variable which is kept for the whole program execution needs to be declared outside functions.

As a visibility specifier

The static keyword in C, when used as a top-level declaration, makes the variable or function visible to its own compilation unit only. Modern programming languages generally uses namespaces to avoid name clashes, so this use isn't widely adopted apart from programming languages with C compatibility in mind (e.g. C++, Objective-C). Other programming languages which support visibility declarations at top-level use a variety of other keywords to specify different level of visibility, for example, public in Java for classes which can be used everywhere, or internal / file in C#.[4]

As a class member specifier

The static keyword is used in most programming languages with classes to specify a member to be a class member, instead of an instance member, inherited from the usage of C++.

A static member of a class has the following characteristics:

  • Independent from any class instances, can be accessed using the class name instead of an expression having the class object type.
  • For fields: exist throughout the program lifetime (i.e. having static storage duration).
  • For methods: cannot access any non-static members without an object expression (implicitly referring to the current instance), or the this reference for the current instance.

Some programming languages even go further, allowing the use of static keyword in other places in a class declaration or usage, for example:

  • Static initialisers in Java and JavaScript, which are run once when the class is loaded
  • Static constructors in C#, which are run once before the class is used
  • Static classes in C#, which can't be instantiated.
  • Inner classes in Java implicitly carry a this reference to the outer class object and must exist in the context of an outer class instance. By declaring an inner class to be static, it does not carry such a reference and can be used independently to an outer class instance.
  • The static keyword can be used in place of an actual class name to access static members to provide class-level polymorphism, called late static bindings[5]

As a specifier for closures

The static keyword can be used in some programming languages on anonymous functions to prevent capturing states which are captured by default. It is similar to static local variables and static class members in the sense that a static closure does not depend on the running invocation of the containing function.

  • PHP: Closures constructed in an instance method have the $this reference automatically bound to it, the static keyword prevents this.
  • C#: Closures by default have all local and instance variables captured in it, the static keyword specifies that no outside states to be captured.[6]

See also

References

  1. ^ "MUL TIC SYSTEf·-1-PROGRAMMERS' MANUAL" (PDF).
  2. ^ a b Kernighan, B. W. A TUTORIAL INTRODUCTION TO THE LANGUAGE B (PDF). Murray Hill, New Jersey: Bell Laboratories. p. 4.
  3. ^ "Storage-class specifiers". cppreference.com.
  4. ^ "Access Modifiers (C# Programming Guide)". Microsoft.
  5. ^ "Late Static Bindings". PHP Manual.
  6. ^ "Static anonymous functions". Microsoft.

Read other articles:

Timothy Carey Información personalNacimiento 11 de marzo de 1929 Nueva York (Estados Unidos) Fallecimiento 11 de mayo de 1994 (65 años)Los Ángeles (Estados Unidos) Causa de muerte Accidente cerebrovascular Sepultura Rose Hills Memorial Park Residencia Brooklyn Nacionalidad EstadounidenseLengua materna Inglés Información profesionalOcupación Actor, director de cine, guionista, actor de televisión, actor de cine y productor de cine Años activo desde 1951Sitio web www.timothycarey.com &#...

 

María của Áo và Bồ Đào NhaHoàng hậu La Mã Thần thánhTại vị25 tháng 7 năm 1564 – 12 tháng 10 năm 1576 (12 năm, 79 ngày)Tiền nhiệmIsabel của Bồ Đào NhaKế nhiệmAnna của Áo-TirolVương hậu nước Đức và Bohemia Đại vương công phu nhân ÁoTại vị25 tháng 7 năm 1564 – 12 tháng 10 năm 1576 (−12 năm, 79 ngày)Tiền nhiệmAnna của Hungary và BohemiaKế nhiệmAnna của Áo-TyrolVương hậu HungaryTại v

 

Футбол для дружби (англ. Football for Friendship) — щорічна міжнародна дитяча соціальна програма, яку реалізує ПАТ «Газпром». Мета програми — через футбол прищепити молодому поколінню актуальні цінності та інтерес до здорового способу життя[1]. У рамках програми футболісти віко

Wakil Bupati Nagan RayaPetahanaH. Chalidin Oesman, S.E., M.M.sejak 9 Oktober 2017Masa jabatan5 tahunDibentuk2007Pejabat pertamaM. Kasem Ibrahim, B.Sc.Situs webwww.naganrayakab.go.id Berikut ini adalah daftar Wakil Bupati Nagan Raya dari masa ke masa. No Wakil Bupati Mulai Jabatan Akhir Jabatan Prd. Ket. Bupati 1 M. Kasem IbrahimB.Sc. 30 Maret 2007 30 Maret 2012 1   Drs. H.Teuku Zulkarnaini Jabatan kosong 4 April 2012 8 Oktober 2012 -   H.AzwirS.Sos.(Penjabat) 2 H. M.Jamin Idham...

 

British TV series or programme Great ExpectationsGenreHistorical dramaBased onGreat Expectations1861 novelby Charles DickensWritten byHugh LeonardDirected byAlan BridgesStarringGary Bond Francesca Annis Maxine AudleyCountry of originUnited KingdomOriginal languageEnglishNo. of series1No. of episodes10ProductionProducerCampbell LoganRunning time25 minutesProduction companyBBCOriginal releaseNetworkBBC OneRelease22 January (1967-01-22) –26 March 1967 (1967-03-26) Great Exp...

 

2012 American romantic comedy-drama film by David O. Russell Silver Linings PlaybookTheatrical release posterDirected byDavid O. RussellScreenplay byDavid O. RussellBased onThe Silver Linings Playbookby Matthew QuickProduced by Donna Gigliotti Bruce Cohen Jonathan Gordon Starring Bradley Cooper Jennifer Lawrence Robert De Niro Jacki Weaver Anupam Kher Chris Tucker CinematographyMasanobu TakayanagiEdited by Jay Cassidy Crispin Struthers Music byDanny ElfmanProductioncompanyThe Weinstein Compan...

Police Department of Lucknow City Lucknow Police Commissionerateलखनऊ पुलिस आयुक्तालयLogoFlag of Uttar Pradesh PoliceAbbreviationLPMotto।। वयं रक्षणाय सेवामहे ।। SanskritAgency overviewFormed14 January 2020; 3 years ago (14 January 2020)Jurisdictional structureOperations jurisdictionMetropolitan Region, Lucknow, IndiaLucknow Police Jurisdictional AreaSize631 km2 (244 sq mi)PopulationMore T...

 

Discography for a multimedia webcomic What Pumpkin redirects here. For Andrew Hussie's online store, see MS Paint Adventures. The 2009 webcomic Homestuck, written and drawn by Andrew Hussie, currently holds a soundtrack consisting of 30 digital albums. Besides static images, Homestuck makes use of flash animations and games, which often involve background music. The music of Homestuck is composed by fans, but is published by Hussie through his Bandcamp page under the What Pumpkin record label...

 

Map all coordinates using: OpenStreetMap Download coordinates as: KML GPX (all coordinates) GPX (primary coordinates) GPX (secondary coordinates) Suburb of Sunshine Coast, Queensland, AustraliaSippy DownsSunshine Coast, QueenslandUniversity of the Sunshine Coast, 2019Sippy DownsCoordinates26°43′24″S 153°05′04″E / 26.7233°S 153.0844°E / -26.7233; 153.0844 (Sippy Downs (centre of suburb))Population11,544 (SAL 2021)[1]Postcode(s)4556Area14...

English footballer Willie Appleyard Appleyard for NewcastlePersonal informationFull name Willie AppleyardDate of birth (1878-08-13)13 August 1878Place of birth Caistor, England[1]Date of death 14 January 1958(1958-01-14) (aged 79)Place of death Newcastle, EnglandPosition(s) Centre forwardSenior career*Years Team Apps (Gls)1901–1902 Grimsby Town 44 (19)1902–1908 Newcastle United 126 (71)1908 Oldham Athletic 1908–1909 Grimsby Town 13 (2)1909 Mansfield Mechanics *Club domestic...

 

الجمعية الثيوصوفيةالشعارالتاريخالتأسيس 17 نوفمبر 1875 المؤسس هيلينا بتروفنا بلافاتسكي الإطارالنوع منظمة دينية[1] المقر الرئيسي تشيناي على الخريطة التنظيمالدين ثيوصوفية موقع الويب sociedadteosofica.es تعديل - تعديل مصدري - تعديل ويكي بيانات جزء من سلسلة مقالات عنالثِّيوصوفيَّة ...

 

Medical conditionGestational pemphigoidOther namesPemphigoid gestationis, herpes gestationis[1]Micrograph of gestational pemphigoid showing the characteristic subepidermal blisters and abundant eosinophils. HPS stain.SpecialtyDermatologySymptomsBlisters, itch, hives[1]ComplicationsPremature delivery of a small baby, a few who may be born with blisters and urticaria[1]Usual onsetMiddle of pregnancy or shortly after[1]DurationAround 6-months[1]CausesAutoi...

This article has multiple issues. Please help improve it or discuss these issues on the talk page. (Learn how and when to remove these template messages) This article relies excessively on references to primary sources. Please improve this article by adding secondary or tertiary sources. Find sources: Lourdes Health System – news · newspapers · books · scholar · JSTOR (September 2015) (Learn how and when to remove this template message) This article ne...

 

Garukan kucing dengan tinggi 6 kaki. Garukan kucing (atau tempat garukan) adalah sebuah tempat perlengkapan hewan peliharaan yang terbuat dari kayu dan dilapisi dengan bahan kasar yang disediakan oleh pemilik kucing kepada kucing peliharaanya agar kucing tersebut dapat menggaruk di tempat yang telah disediakan. Kucing memiliki keinginan alami untuk menggaruk: tindakan yang dapat membantu kucing untuk mengasah kukunya dan untuk menandai wilayah mereka dengan kelenjar bau di kaki mereka. Penyed...

 

Latvian ice hockey player Ice hockey player Edgars Masaļskis Born (1980-03-31) 31 March 1980 (age 43)Riga, Latvian SSR, Soviet UnionHeight 5 ft 9 in (175 cm)Weight 172 lb (78 kg; 12 st 4 lb)Position GoaltenderCaught LeftPlayed for HK Lido Nafta RigaHK RigaHK Liepājas MetalurgsHC Sibir NovosibirskMörrums GoIS IKHC Karlovy VaryDukla JihlavaIHC PísekNeftyanik AlmetievskEHC FreiburgMetallurg ZhlobinDinamo RigaEV Duisburg Die FüchseHC YugraHK PopradHC A...

Franklin Field, where the Penn Quakers have played their home games since 1895. This is a list of seasons completed by the Penn Quakers football team of the National Collegiate Athletic Association (NCAA) Division I Football Championship Subdivision (FCS). Since the team's first season in 1876, the Quakers have competed in nearly than 1,500 officially sanctioned games,[1] holding an all-time record of 878–509–42.[2] Penn joined the Ivy League as a founding member in 1956.&...

 

Provincial cricket competition on the island of Ireland The NCU Challenge Cup, also called the NCU Senior Challenge Cup and the NCU Senior Cup, is the most important provincial cricket knock-out cup of the NCU jurisdiction in Ireland. The competition began in 1887, with eleven clubs participating in the first competition, North Down eventually beating North of Ireland in the final at Ormeau.[1] The Cup is open to teams playing in the Premier League and Section 1 of the NCU Senior Leag...

 

MarjoBackground informationBirth nameMarjolène MorinBorn (1953-08-02) 2 August 1953 (age 70)Montreal, Quebec, CanadaGenresrock, popOccupation(s)singer, songwriterInstrument(s)vocalsYears active1979–presentMusical artist Marjolène Morin (born 2 August 1953), professionally known as Marjo, is a Canadian singer-songwriter from Quebec.[1] Background Morin was born and raised in Montreal, Quebec.[2] She worked as a model and editor for the fashion magazine Madame, and as m...

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. (August 2021) Abraham Mordechai PiurkoNative nameאברהם מרדכי פּיורקאָBorn(1853-02-15)15 February 1853Lomza, Augustów Governorate, Congress PolandDied11 June 1933(1933-06-11) (aged 80)Grayeve, Bialystok Voivodeship, Second Polish RepublicLanguageHebrew Abraham Mordechai Piurko (Yiddish: אברהם מרדכי פּ...

 

יהושע בן גמלא היה השם של כהן גדול, או מספר כהנים גדולים בימי בית המקדש השני. יהושע בן גמלא מוזכר בספריו של יוסף בן מתתיהו, ככהן גדול במחצית הראשונה של שנות ה-60 של המאה ה-1 וממנהיגי ממשלת המרד המתונה בזמן המרד הגדול ערב חורבן בית המקדש השני. בתלמוד, מוזכר יהושע בן גמלא ככהן גדול ...

 

Strategi Solo vs Squad di Free Fire: Cara Menang Mudah!