Side effect (computer science)

In computer science, an operation, function or expression is said to have a side effect if it has any observable effect other than its primary effect of reading the value of its arguments and returning a value to the invoker of the operation. Example side effects include modifying a non-local variable, a static local variable or a mutable argument passed by reference; raising errors or exceptions; performing I/O; or calling other functions with side-effects.[1] In the presence of side effects, a program's behaviour may depend on history; that is, the order of evaluation matters. Understanding and debugging a function with side effects requires knowledge about the context and its possible histories.[2][3] Side effects play an important role in the design and analysis of programming languages. The degree to which side effects are used depends on the programming paradigm. For example, imperative programming is commonly used to produce side effects, to update a system's state. By contrast, declarative programming is commonly used to report on the state of system, without side effects.

Functional programming aims to minimize or eliminate side effects. The lack of side effects makes it easier to do formal verification of a program. The functional language Haskell eliminates side effects such as I/O and other stateful computations by replacing them with monadic actions.[4][5] Functional languages such as Standard ML, Scheme and Scala do not restrict side effects, but it is customary for programmers to avoid them.[6]

Effect systems extend types to keep track of effects, permitting concise notation for functions with effects, while maintaining information about the extent and nature of side effects. In particular, functions without effects correspond to pure functions.

Assembly language programmers must be aware of hidden side effects—instructions that modify parts of the processor state which are not mentioned in the instruction's mnemonic. A classic example of a hidden side effect is an arithmetic instruction that implicitly modifies condition codes (a hidden side effect) while it explicitly modifies a register (the intended effect). One potential drawback of an instruction set with hidden side effects is that, if many instructions have side effects on a single piece of state, like condition codes, then the logic required to update that state sequentially may become a performance bottleneck. The problem is particularly acute on some processors designed with pipelining (since 1990) or with out-of-order execution. Such a processor may require additional control circuitry to detect hidden side effects and stall the pipeline if the next instruction depends on the results of those effects.

Referential transparency

Absence of side effects is a necessary, but not sufficient, condition for referential transparency. Referential transparency means that an expression (such as a function call) can be replaced with its value. This requires that the expression is pure, that is to say the expression must be deterministic (always give the same value for the same input) and side-effect free.

Temporal side effects

Side effects caused by the time taken for an operation to execute are usually ignored when discussing side effects and referential transparency. There are some cases, such as with hardware timing or testing, where operations are inserted specifically for their temporal side effects e.g. sleep(5000) or for (int i = 0; i < 10000; ++i) {}. These instructions do not change state other than taking an amount of time to complete.

Idempotence

A subroutine with side effects is idempotent if multiple applications of the subroutine have the same effect on the system state as a single application, in other words if the function from the system state space to itself associated with the subroutine is idempotent in the mathematical sense. For instance, consider the following Python program:

x = 0

def setx(n):
    global x
    x = n

setx(3)
assert x == 3
setx(3)
assert x == 3

setx is idempotent because the second application of setx to 3 has the same effect on the system state as the first application: x was already set to 3 after the first application, and it is still set to 3 after the second application.

A pure function is idempotent if it is idempotent in the mathematical sense. For instance, consider the following Python program:

def abs(n):
    return -n if n < 0 else n

assert abs(abs(-3)) == abs(-3)

abs is idempotent because the second application of abs to the return value of the first application to -3 returns the same value as the first application to -3.

Example

One common demonstration of side effect behavior is that of the assignment operator in C. The assignment a = b is an expression that evaluates to the same value as the expression b, with the side effect of storing the R-value of b into the L-value of a. This allows multiple assignment:

a = (b = 3);  // b = 3 evaluates to 3, which then gets assigned to a

Because the operator right associates, this is equivalent to

a = b = 3;

This presents a potential hangup for novice programmers who may confuse

while (b == 3) {}  // tests if b evaluates to 3

with

while (b = 3) {}  // b = 3 evaluates to 3, which then casts to true so the loop is infinite

See also

References

  1. ^ Spuler, David A.; Sajeev, A. Sayed Muhammed (January 1994). Compiler Detection of Function Call Side Effects. James Cook University. CiteSeerX 10.1.1.70.2096. The term Side effect refers to the modification of the nonlocal environment. Generally this happens when a function (or a procedure) modifies a global variable or arguments passed by reference parameters. But here are other ways in which the nonlocal environment can be modified. We consider the following causes of side effects through a function call: 1. Performing I/O. 2. Modifying global variables. 3. Modifying local permanent variables (like static variables in C). 4. Modifying an argument passed by reference. 5. Modifying a local variable, either automatic or static, of a function higher up in the function call sequence (usually via a pointer).
  2. ^ Turner, David A., ed. (1990). Research Topics in Functional Programming. Addison-Wesley. pp. 17–42. Via Hughes, John. "Why Functional Programming Matters" (PDF). Archived (PDF) from the original on 2022-06-14. Retrieved 2022-08-06.
  3. ^ Collberg, Christian S. (2005-04-22). "CSc 520 Principles of Programming Languages". Department of Computer Science, University of Arizona. Archived from the original on 2022-08-06. Retrieved 2022-08-06.
  4. ^ "Haskell 98 report". 1998.
  5. ^ Jones, Simon Peyton; Wadler, Phil (1993). Imperative Functional Programming. Conference Record of the 20th Annual ACM Symposium on Principles of Programming Languages. pp. 71–84.
  6. ^ Felleisen, Matthias; Findler, Robert Bruce; Flatt, Matthew; Krishnamurthi, Shriram (2014-08-01). "How To Design Programs" (2 ed.). MIT Press.

Read other articles:

Artikel ini bukan mengenai Adsorpsi. Untuk penyerapan cahaya, lihat absorbansi. Penjerap laboratorium. 1a): CO2 inlet; 1b): H2O inlet; 2): outlet 3): kolom absorpsi; 4): kemasan. 1. Tangki Penampung 2. Kran pengatur debit air 3. Tangki overflow 4. Saluran overflow 5. Floatmeter 6. Menara bahan isian 7. Kompresor 8. Botol penampung umpan 9. Manometer gas 10. Erlenmeyer 250 mL 11. Larutan H2SO4 penyerap Dalam ilmu kimia, absorpsi atau penyerapan[1] adalah fenomena fisika atau kimia atau...

 

8th U.S. Secretary of Health and Human Services For other people named Michael Leavitt, see Michael Leavitt (disambiguation). Mike Leavitt20th United States Secretary of Health and Human ServicesIn officeJanuary 26, 2005 – January 20, 2009PresidentGeorge W. BushPreceded byTommy ThompsonSucceeded byKathleen Sebelius10th Administrator of the Environmental Protection AgencyIn officeNovember 6, 2003 – January 26, 2005PresidentGeorge W. BushPreceded byChristine Todd WhitmanSu...

 

Village in Estonia Village in Harju County, EstoniaMeremõisaVillageCountry EstoniaCountyHarju CountyParishLääne-Harju ParishPopulation (31 December 2021[1]) • Total163Time zoneUTC+2 (EET) • Summer (DST)UTC+3 (EEST) Meremõisa is a village in Lääne-Harju Parish, Harju County in northern Estonia.[2] Meremõisa is about 27 km (17 mi) west of the capital Tallinn, west of Keila-Joa, and next to Lohusalu Bay, which is part of the Gulf...

For the penny fiction weekly, see The London Journal. James Boswell James Boswell's London Journal is a published version of the daily journal he kept between the years 1762 and 1763 while in London. Along with many more of his private papers, it was found in the 1920s at Malahide Castle in Ireland, and was first published in 1950, in an edition by Frederick A. Pottle. In it, Boswell, then a young Scotsman of 22, visits London for his second time. One of the most notable events in the journal...

 

Pour les articles homonymes, voir Jack McCarthy. Jack McCarthy Biographie Nom John Joseph McCarthy Nationalité Irlandais Naissance 29 mars 1898 Londres (Angleterre) Décès 10 mars 1958 (à 59 ans) Dublin (Irlande) Poste Défenseur Parcours professionnel1 AnnéesClub 0M.0(B.) ? Olympia ? Bohemian Sélections en équipe nationale2 AnnéesÉquipe 0M.0(B.) 1921 Irlande Amateurs (IFA) 00? 0(?) 1924 League of Ireland XI 001 0(0) 1924-1930 État Libre d'Irlande 006 0(0) 1 Compétitions offic...

 

Jalal Mirzayev Duta Besar Azerbaijan untuk IndonesiaMasa jabatan27 September 2019 – sekarangPresidenIlham AliyevPendahuluTamerlan GarayevPenggantiPetahana Informasi pribadiLahir17 Oktober 1977 (umur 46)Masally, RSS Azerbaijan, Uni Soviet (kini Azerbaijan)KebangsaanAzerbaijanAnak3PekerjaanYurisSunting kotak info • L • B Jalal Sabir Mirzayev (bahasa Azerbaijan: Cəlal Sabir oğlu Mirzəyev) (lahir 17 Oktober 1977) diplomat, Duta Besar Luar Biasa dan Berkuasa Penuh ...

1931 1939 Élection présidentielle française de 1932 10 mai 1932 Corps électoral et résultats Votants 826 Blancs et nuls 49 Albert Lebrun – AD Voix 633 81,5 %  Paul Faure – SFIO Voix 114 14,7 %  Président de la République Sortant Élu Paul Doumer RI Albert Lebrun AD modifier - modifier le code - voir Wikidata  Une élection présidentielle se tient en France le 10 mai 1932 afin d'élire le président de la République à la suite de l'assassin...

 

Division of Air India Limited This article is about a defunct airline. For other airlines of India, see List of airlines of India. 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: Indian Airlines – news · newspapers · books · scholar · JSTOR (July 2012) (Learn how and when to remove this message) Indian Airli...

 

Cet article est une ébauche concernant un coureur cycliste espagnol. Vous pouvez partager vos connaissances en l’améliorant (comment ?). Pour plus d’informations, voyez le projet cyclisme. Delio RodríguezInformationsNom de naissance Delio Rodríguez BarrosNaissance 19 avril 1916PonteareasDécès 14 janvier 1994 (à 77 ans)VigoNationalité espagnoleÉquipes professionnelles 1943CF Barcelona1946Galindo-Tabay1946Fabas1948Peugeot-Dunlop1948Sangalhos1948Paloma1948FiorelliPrincipa...

Cet article est une ébauche concernant une localité écossaise. Vous pouvez partager vos connaissances en l’améliorant (comment ?) selon les recommandations des projets correspondants. Torphins en écossais : Tòrr Fionn Ecole primaire de Torphins Administration Pays Royaume-Uni Nation Écosse Council area Aberdeenshire Force de police Police Scotland Incendie Scottish Fire and Rescue Service Ambulance Scottish Ambulance Service Démographie Population 1 410 hab. (20...

 

土库曼斯坦总统土库曼斯坦国徽土库曼斯坦总统旗現任谢尔达尔·别尔德穆哈梅多夫自2022年3月19日官邸阿什哈巴德总统府(Oguzkhan Presidential Palace)機關所在地阿什哈巴德任命者直接选举任期7年,可连选连任首任萨帕尔穆拉特·尼亚佐夫设立1991年10月27日 土库曼斯坦土库曼斯坦政府与政治 国家政府 土库曼斯坦宪法 国旗 国徽 国歌 立法機關(英语:National Council of Turkmenistan) ...

 

جورج ميريديث (بالإنجليزية: George Meredith)‏  معلومات شخصية الميلاد 12 فبراير 1828(1828-02-12)بورتسموث الوفاة 18 مايو 1909 (81 سنة)دوركينغ[1]  مكان الدفن سري  مواطنة المملكة المتحدة لبريطانيا العظمى وأيرلندا المملكة المتحدة  الحياة العملية الحركة الأدبية ما قبل الرفائيلية  ا...

Pour les articles homonymes, voir Amoroso (homonymie). Gigi l'amoroso Disque du single, face A. Single de Dalidaextrait de l'album Dalida (Manuel) Face A Gigi l'amoroso Face B Il venait d'avoir 18 ans Durée 7:28 Genre Chanson française modifier Gigi l'amoroso est une chanson interprétée par Dalida en 1974[1], écrite par Michaële, L. et P. Sebastien et R. Rinaldi[2]. En 1974, Dalida remonte sur la scène de l'Olympia et présente une nouvelle chanson, Gigi l'amoroso. Le titre se ve...

 

Лаппо-Данилевський Олександр СергійовичНародився 15 (27) січня 1863Верхньодніпровський повіт, Катеринославська губернія, Російська імперіяПомер 7 лютого 1919(1919-02-07)[1] (56 років)Петроград, Російська СФРР[1]·сепсисПоховання Державний історико-меморіальний Лук'янівськи�...

 

This article is about the racehorse. For the generic topic, see World domination. This article is about the Epsom Derby winner. For the Grand National winner, see Rule The World (horse). Thoroughbred racehorse Ruler of the WorldRuler of the World at the start of the 2013 Epsom Derby.SireGalileoGrandsireSadler's WellsDamLove Me TrueDamsireKingmamboSexColtFoaled17 March 2010CountryIrelandColourChestnutBreederSouthern BloodstockOwnerMrs John MagnierMichael TaborDerrick SmithAl Shaqab RacingTrain...

Questa voce sull'argomento calciatori irlandesi è solo un abbozzo. Contribuisci a migliorarla secondo le convenzioni di Wikipedia. Segui i suggerimenti del progetto di riferimento. Lee CarsleyCarsley con la divisa dell'Everton.Nazionalità Irlanda Altezza180 cm Peso76 kg Calcio RuoloAllenatore (ex centrocampista) Squadra Inghilterra U-21 Inghilterra (Ad Interim) Termine carriera1º luglio 2011 - giocatore CarrieraSquadre di club1 1992-1999 Derby County138 (5)1999-2000 Bl...

 

Voce principale: Torino Football Club. Torino CalcioStagione 1987-1988 Sport calcio Squadra Torino Allenatore Luigi Radice Presidente Mario Gerbi Serie A7º[1] Coppa ItaliaFinalista Maggiori presenzeCampionato: Lorieri, Rossi (30)Totale: Lorieri (44) Miglior marcatoreCampionato: Polster (9)Totale: Polster (14) StadioComunale Vittorio Pozzo Maggior numero di spettatori54 860 vs Juventus(3 gennaio 1988) Minor numero di spettatori17 146 vs Empoli(13 dicembre 1987) Media s...

 

腓尼基𐤊𐤍𐤏𐤍‬ Φοινίκη前2500年—前539年腓尼基地圖首都比布魯斯 (2500-1000 BC)泰爾 (900-550 BC)[1]常用语言腓尼基語、布匿語宗教古迦南宗教(英语:Ancient_Canaanite_religion)政府君主制(城邦联盟)[2]著名的腓尼基城邦国王 • 约前1000年 阿希拉姆(英语:Ahiram sarcophagus)(比布鲁斯)• 前969年–前936年 希拉姆一世(英语:Hiram I)(比布鲁斯�...

This is an archive of past discussions. Do not edit the contents of this page. If you wish to start a new discussion or revive an old one, please do so on the current talk page. Archives 2023;Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2022;Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2021;Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2020;Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2019;Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec 2018;Jan Feb Mar Apr May Jun Jul Aug Sep Oct ...

 

1975 film by Emil Loteanu Gypsies Are Found Near HeavenOriginal film posterDirected byEmil LoteanuWritten byMaxim Gorky (story)Emil LoteanuProduced byMosfilmStarringSvetlana TomaGrigore GrigoriuBarasbi MulayevMikhail ShishkovBorislav BrondukovVasyl SymchychCinematographySergei VronskyEdited byNadezhda VasilyevaMusic byEugen DogaProductioncompanyMosfilmDistributed bySovexportfilm (US)Release dates 1975 (1975) 20 October 1976 (1976-10-20) (Toronto Festival of Festivals) ...