Label (computer science)

In programming languages, a label is a sequence of characters that identifies a location within source code. In most languages, labels take the form of an identifier, often followed by a punctuation character (e.g., a colon). In many high-level languages, the purpose of a label is to act as the destination of a GOTO statement.[1][2] In assembly language, labels can be used anywhere an address can (for example, as the operand of a JMP or MOV instruction).[3] Also in Pascal and its derived variations. Some languages, such as Fortran and BASIC, support numeric labels.[4] Labels are also used to identify an entry point into a compiled sequence of statements (e.g., during debugging).

C

In C a label identifies a statement in the code. A single statement can have multiple labels. Labels just indicate locations in the code and reaching a label has no effect on the actual execution.

Function labels

Function labels consist of an identifier, followed by a colon. Each such label points to a statement in a function and its identifier must be unique within that function. Other functions may use the same name for a label. Label identifiers occupy their own namespace – one can have variables and functions with the same name as a label.

void foo(int number)
{
    if (number < 0)
        goto error;
    bar(number);
    return;
error:
    fprintf(stderr, "Invalid number!\n");
}

Here error is the label. The statement goto can be used to jump to a labeled statement in the code. After a goto, program execution continues with the statement after the label.

Switch labels

Two types of labels can be put in a switch statement. A case label consists of the keyword case, followed by an expression that evaluates to integer constant. A default label consists of the keyword default. Case labels are used to associate an integer value with a statement in the code. When a switch statement is reached, program execution continues with the statement after the case label with value that matches the value in the parentheses of the switch. If there is no such case label, but there is a default label, program execution continues with the statement after the default label. If there is no default label, program execution continues after the switch.

switch (die)
{
default:
    printf("invalid\n");
    break;

case 1:
case 3:
case 5:
    printf("odd\n");
    break;

case 2:
case 4:
case 6:
    printf("even\n");
    break;
}

Within a single switch statement, the integer constant associated with each case label must be unique. There may or may not be a default statement. There is no restriction on the order of the labels within a switch. The requirement that case labels values evaluate to integer constants gives the compiler more room for optimizations.

Examples

Javascript

In JavaScript language syntax statements may be preceded by the label:

top: //Label the outermost for-loop.
for (var i = 0; i < 4; i++) {
    for (var j = 0; j < 4; j++) {
        if (j === 3 && i === 2) {
            alert("i=" + i + ", j=" + j); //i=2, j=3
            break top;
        }
    }
}

alert("i=" + i + ", j=" + j); //i=2, j=3

It also possible to use break statement to break out of the code blocks:

top: {
  console.log("foo")
  console.log("bar")
  break top
  console.log("baz")

}
// Which would output: 
// > foo
// > bar

Common Lisp

In Common Lisp two ways of defining labels exist. The first one involves the tagbody special operator. Distinguishing its usage from many other programming languages that permit global navigation, such as C, the labels are only accessible in the context of this operator. Inside of a tagbody labels are defined as forms starting with a symbol; the go special form permits a transfer of control between these labels.[5]

(let ((iteration NIL))
  (tagbody
    start
      (print 'started)
      (setf  iteration 0)
    increase
      (print iteration)
      (incf  iteration 1)
      (go    check)
    check
      (if (>= iteration 10)
        (go end)
        (go increase))
    end
      (print 'done)))

A second method utilizes the reader macros #n= and #n#, the former of which labels the object immediately following it, the latter refers to its evaluated value.[6] Labels in this sense constitute rather an alternative to variables, with #n= declaring and initializing a “variable” and #n# accessing it. The placeholder n designates a chosen unsigned decimal integer identifying the label.

(progn
  #1="hello"
  (print #1#))

Apart from that, some forms permit or mandate the declaration of a label for later referral, including the special form block which prescribes a naming, and the loop macro that can be identified by a named clause. Immediate departure from a named form is possible by using the return-from special operator.

(block myblock
  (loop for iteration from 0 do
    (if (>= iteration 10)
      (return-from myblock 'done)
      (print iteration))))
(loop
  named myloop
  for   iteration from 0
  do    (if (>= iteration 10)
          (return-from myloop 'done)
          (print iteration)))

In a fashion similar to C, the macros case, ccase, ecase,[7] typecase, ctypecase and etypecase define switch statements.[8]

(let ((my-value 5))
  (case my-value
    (1         (print "one"))
    (2         (print "two"))
    ((3 4 5)   (print "three four or five"))
    (otherwise (print "any other value"))))
(let ((my-value 5))
  (typecase my-value
    (list      (print "a list"))
    (string    (print "a string"))
    (number    (print "a number"))
    (otherwise (print "any other type"))))

See also

References

  1. ^ "C Standard section 6.8.6.1 The goto statement". Archived from the original on 2007-12-24. Retrieved 2008-07-03.
  2. ^ "GOTO Statement QuickSCREEN". Microsoft. 1988. Archived from the original on 2009-07-25. Retrieved 2008-07-03.
  3. ^ O. Lawlor. "nasm x86 Assembly". Retrieved 2008-07-03.
  4. ^ "Differences Between GW-BASIC and QBasic". Archived from the original on 2010-02-10.
  5. ^ Kent Pitman. "CLHS: Special Operator TAGBODY". Retrieved 2020-08-18.
  6. ^ Kent Pitman. "CLHS: Section 2.4.8". Retrieved 2020-08-18.
  7. ^ Kent Pitman. "CLHS: Macro CASE, CCASE, ECASE". Retrieved 2020-08-20.
  8. ^ Kent Pitman. "CLSH: Macro TYPECASE, CTYPECASE, ETYPECASE". Retrieved 2020-08-20.

Read other articles:

För andra betydelser, se Øyafestivalen (olika betydelser). Øyafestivalen är en musikfestival som hålls årligen i Oslo. Sedan 2014 äger festivalen rum i Tøyenparken och dessförinnan i Middelalderparken. Festivalen arrangerades för första gången 1999. Källor Den här artikeln är helt eller delvis baserad på material från norska Wikipedia (bokmål/riksmål), Øyafestivalen, 16 augusti 2014.  Denna artikel om ett evenemang saknar väsentlig information. Du kan hjälpa till ge...

 

 

Overview of the state of capital punishment in Austria Europe holds the greatest concentration of abolitionist states (blue). Map current as of 2022   Abolished for all offences   Abolished in practice   Retains capital punishment Capital punishment in Austria was abolished in 1787, although restored in 1795. Unlike other countries with a minimum age of 18, the Habsburg Law enacted in 1919 set the minimum age for execution in Austria to 20. The method of executio...

 

 

Леванლევან ბატონიშვილი Царь Картли 1709 Предшественник Вахтанг VI Преемник Кайхосро Рождение ок. 1660 Смерть 13 июля 1709(1709-07-13)Исфахан (Персия) Отец Вахтанг V Мать Родам Баташвили-Орбелишвили (Орбелиани) Супруга 1) Тута Гуриели 2) Тинатин Авалишвили Дети от 1-го брака: Кай...

إنترلوكين 17 (بالإنجليزية: Interleukin 17)‏ ومختصره (IL-17) هي مجموعة سيتوكين تعرف بعائلة إنترلوكين 17 عرفت أول مرة عام 1993 على أنها نسخ من ورم هجين لخلية تائية لقارض.[1][2][3] إنترلوكين 17 هي سيتوكينات وسيطة قوية في تفاعلات النوع المتأخر من خلال زيادة إنتاج كيموكين في الأنسجة ال

 

 

Jamaah TablighIjtima Tahunan Jamaah Tabligh Malaysia 2009Sepang Selangor, MalaysiaTotal populasi12 hingga 80 juta[1]PendiriMuhammad Ilyas al-Kandhlawi[2]AgamaIslam Deobandi[2][3][4]Kitab suciQuran, Hadis, dan Sunnah Bagian dari seriIslam Rukun Iman Keesaan Allah Nabi dan Rasul Allah Kitab-kitab Allah Malaikat Hari Kiamat Qada dan Qadar Rukun Islam Syahadat Salat Zakat Puasa Haji Sumber hukum Islam al-Qur'an Sunnah (Hadis, Sirah) Tafsir Akidah Fikih Syar...

 

 

Untuk kegunaan lain dari Stabschef, lihat Kepala Staf. StabschefElang Reich Jerman Bendera komando awal (kiri) dan masa berikutnya (kanan)Pemegang jabatan terkenalErnst Röhm5 Januari 1931 – 1 Juli 1934SturmabteilungStatusPerwira komando organisasi paramiliterAnggotaOberste SA-FührungAtasanOberste SA-FührerDitunjuk olehAdolf HitlerDibentukOktober 1929Pejabat pertamaOtto WagenerPejabat terakhirWilhelm SchepmannJabatan dihapus5 Mei 1945Wakil Stabsführer Stabschef ([ʃtaːps.ʃɛf], Kepala ...

?Морський крайт Морський крайт звичайний Біологічна класифікація Домен: Ядерні (Eukaryota) Царство: Тварини (Animalia) Тип: Хордові (Chordata) Підтип: Черепні (Craniata) Інфратип: Хребетні (Vertebrata) Клас: Плазуни (Reptilia) Ряд: Лускаті (Squamata) Підряд: Змії (Serpentes) Родина: Аспідові (Elapidae) Підродина: Мор...

 

 

Gedenktafel für Aloys Ruppel am Gutenbergmuseum Mainz Aloys Leonhard Ruppel (* 21. Juni 1882 in Opperz, heute Gemeindeteil von Neuhof (bei Fulda); † 11. Juli 1977 in Mainz) war ein deutscher Bibliothekar, Archivar und Historiker. Inhaltsverzeichnis 1 Leben 2 Auszeichnungen und Ehrungen 3 Schriften (Auswahl) 4 Literatur 5 Weblinks 6 Einzelnachweise Leben Aloys Ruppel besuchte die Hohe Landesschule in Hanau und legte dort 1904 das Abitur ab. Ab dem Sommersemester 1904 studierte er Geschichte...

 

 

Pilbara Wanderer and Dog of Northwestern Australia Red DogRed Dog statue.Other name(s)Bluey Dog of the NorthwestSpeciesDogBreedkelpie/cattle dog crossbreed dogSexMaleBornTally Ho1971 (1971)Paraburdoo, Western AustraliaDied21 November 1979(1979-11-21) (aged 7–8)Karratha, Western AustraliaResting placeSecret location, Roebourne, Western AustraliaKnown forTravelling throughout Western Australia's Pilbara regionTitleThe Pilbara WandererOwnerColin Cummings (former) John Stazzonell...

Tramwaje w Wenecji tramwaj Translohr w Wenecji Państwo  Włochy Lokalizacja Wenecja Operator ACTV Liczba linii 1 Lata funkcjonowania od 2010 Infrastruktura Mapka linii tramwajowej w Wenecji Długość sieci 6,3 km Multimedia w Wikimedia Commons Tramwaje w Wenecji – system komunikacji miejskiej typu translohr, który został otwarty 20 grudnia 2010 w miejskiej części Wenecji (Mestre). Pierwszy wniosek, który przewidywał odbudowę linii tramwajowej złożono w 1992. Decyzję o zasto...

 

 

Special committee of the House of Representatives of the Philippines Special Committee onStrategic Intelligence18th CongressHistoryNew session startedJuly 22, 2019 (2019-07-22)LeadershipChairmanJohnny Pimentel (PDP–Laban) since December 7, 2020 StructureSeats12 membersPolitical groupsMajority (11)   Nacionalista (3)   PDP–Laban (3)   Party-lists (2)   NUP (2)   NPC (1) Minority (1)   Party-list (1) WebsiteSpecial Committee on Strategic Inte...

 

 

King of Judah AmonAmon from Guillaume Rouillé's Promptuarii Iconum Insigniorum, 1554King of JudahReign643/642 – 641/640 BC[1][2]PredecessorManassehSuccessorJosiahBornc. 664 BCJudahDiedc. 641 BCJerusalemBurial641 BCGarden of Uzza[3]ConsortJedidah[4]IssueJosiahHebrewאָמוֹןHouseHouse of DavidFatherManassehMotherMeshullemeth[5] Manasseh, Amon and Josiah (16th century print) Amon of Judah[a] was the fifteenth King of Judah who, according to ...

Gothic revival mansion in Scotland Dalmeny HouseDalmeny House, south frontLocationDalmeny, Edinburgh, Scotland, United KingdomCoordinates55°59′17″N 3°20′03″W / 55.988°N 3.3343°W / 55.988; -3.3343OS grid referenceNT168780Built1817Built forArchibald Primrose, 4th Earl of RoseberyArchitectWilliam WilkinsArchitectural style(s)Tudor Gothic Revival Listed Building – Category ADesignated22 February 1971Reference no.LB82 Inventory of Gardens and Designed Lan...

 

 

This article needs a plot summary. Please add one in your own words. (November 2020) (Learn how and when to remove this template message) 2011 American filmThe DynamiterFilm posterDirected byMatthew GordonWritten byBrad IngelsbyProduced byMatthew GordonKevin AbramsMike JonesNate TuckAmile WilsonArt JonesMerilee HoltStarringWilliam Patrick RuffinCinematographyJeffrey WaldronEdited byKevin AbramsBrandon BoydMusic byCasey ImmoorDistributed byFilm MovementRelease date February 2011 (201...

 

 

Ця стаття стосується теми Українська греко-католицька церква Структура Верховний Архієпископ – Святослав (Шевчук) Синод УГКЦ Патріарший собор Воскресіння Христового Богослов'я Катехизм «Христос — наша Пасха» Законодавство Кодекс Канонів Східних Церков Історія Предс...

Cette page concerne l'année 2021 du calendrier grégorien. Chronologies Données clés 2018 2019 2020  2021  2022 2023 2024Décennies :1990 2000 2010  2020  2030 2040 2050Siècles :XIXe XXe  XXIe  XXIIe XXIIIe Chronologies géographiques Afrique Afrique du Sud, Algérie, Angola, Bénin, Botswana, Burkina Faso, Burundi, Cameroun, Cap-Vert, Centrafrique, Comores, République du Congo, République démocratique du Congo, Côte d'Ivoire, Djibouti, Égypte,...

 

 

Campeonato B Nacional 2019 '''Copa Edilberto Acosta'''Datos generalesSede ParaguayCategoría Tercera DivisiónFecha 18 de mayo de 2019 13 de octubre de 2019Edición 9ªPalmarésPrimero Guaraní (Trinidad)Segundo Liga CarapegüeñaDatos estadísticosParticipantes 15 equipos Intercambio de plazas Ascenso(s): Guaraní (Trinidad)Cronología PBN 2018 Campeonato B Nacional 2019 PBN 2021 [editar datos en Wikidata] El Campeonato de la Primera División B Nacional 2019 de la Tercera Divisió...

 

 

Fictional character MangoSaturday Night Live characterChris Kattan as Mango with Horatio Sanz and Tracy MorganFirst appearanceOctober 18, 1997 (S23E03)[1]Last appearanceMay 18, 2002 (S27E20)Created byChris KattanPortrayed byChris KattanIn-universe informationGenderMaleTitleMangoOccupationExotic dancerFamilyGuava, father (Danny DeVito)SpouseMrs. Mango (Molly Shannon)NationalityMango Island Mango is a character performed by Chris Kattan on the American sketch comedy show Saturday Night ...

Halaman ini berisi artikel tentang geografer Bizantium abad ke-6. Untuk biarawan abad ke-7 dati Sisilia, guru Yohanes dari Damaskus dan Kosmas dari Maiuma, lihat Kosmas sang Biarawan. Peta dunia, karya Cosmas Indicopleustes. Peta tersebut berorientasi dengan arah utara di bagian atas. Cosmas Indicopleustes (Yunani Κοσμᾶς Ἰνδικοπλεύστης, artinya Cosmas yang berlayar ke India; yang juga dikenal sebagai Kosmas sang Biarawan) adalah seorang pedagang Yunani dan kemudian eremi...

 

 

Japanese admiral (born 1955) Yasushi MatsushitaBorn1955 (age 67–68)Osaka Prefecture[1]AllegianceJapanService/branchJapan Maritime Self-Defense ForceYears of service?-2014RankAdmiralCommands heldCommander of the Japan Self-Defense ForcesAwardsSee Awards Admiral Yasushi Matsushita (松下泰士, Matsushita Yasushi, born 1955) is a Japanese naval officer who served as the Self Defense Fleet's Commander of the Japanese Maritime Self Defence Force (JMSDF) from 2012 to 2014....

 

 

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