What is short circuiting and how is it used when programming ...
文章推薦指數: 80 %
Short-circuit evaluation means that when evaluating boolean expressions (logical AND and OR ) you can stop as soon as you find the first ... Home Public Questions Tags Users Collectives ExploreCollectives FindaJob Jobs Companies Teams StackOverflowforTeams –Collaborateandshareknowledgewithaprivategroup. CreateafreeTeam WhatisTeams? Teams CreatefreeTeam CollectivesonStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore WhatisshortcircuitingandhowisitusedwhenprogramminginJava?[duplicate] AskQuestion Asked 9years,10monthsago Active 1yearago Viewed 60ktimes 35 17 Thisquestionalreadyhasanswershere: Closed9yearsago. PossibleDuplicate: Doesjavaevaluateremainingconditionsafterbooleanresultisknown Whydoweusuallyuse||not|,whatisthedifference? ImissedmyclasslecturetheotherdayandIwaswonderingifanyonecouldgiveanexplanationwhatshortcircuitingisandmaybeanexampleofitbeingusedinasimpleJavaprogram.Thanksforyourhelp! javashortshort-circuiting Share Improvethisquestion Follow editedMay23'17at12:34 CommunityBot 111silverbadge askedFeb18'12at21:37 user1214845user1214845 1 3 en.wikipedia.org/wiki/Short-circuit_evaluation – Matt Feb18'12at21:42 Addacomment | 5Answers 5 Active Oldest Votes 67 Short-circuitingiswhereanexpressionisstoppedbeingevaluatedassoonasitsoutcomeisdetermined.Soforinstance: if(a==b||c==d||e==f){ //Dosomething } Ifa==bistrue,thenc==dande==fareneverevaluatedatall,becausetheexpression'soutcomehasalreadybeendetermined.ifa==bisfalse,thenc==disevaluated;ifit'strue,thene==fisneverevaluated.Thismaynotseemtomakeanydifference,butconsider: if(foo()||bar()||baz()){ //Dosomething } Iffoo()returnstrue,thenbarandbazarenevercalled,becausetheexpression'soutcomehasalreadybeendetermined.Soifbarorbazhassomeothereffectthanjustreturningsomething(asideeffect),thoseeffectsneveroccur. Onegreatexampleofshort-circuitingrelatestoobjectreferences: if(a!=null&&a.getFoo()!=42){ //Dosomething } a.getFoo()wouldnormallythrowaNullPointerExceptionifawerenull,butbecausetheexpressionshort-circuits,ifa!=nullisfalse,thea.getFoo()partneverhappens,sowedon'tgetanexception. Notethatnotallexpressionsareshort-circuited.The||and&&operatorsareshort-circuited,but|and&arenot,norare*or/;infactmostoperatorsarenot. Share Improvethisanswer Follow editedApr5'17at6:16 DanD. 69.2k1313goldbadges9696silverbadges113113bronzebadges answeredFeb18'12at21:44 T.J.CrowderT.J.Crowder 923k169169goldbadges16981698silverbadges17111711bronzebadges Addacomment | 4 Short-circuitevaluationmeansthatwhenevaluatingbooleanexpressions(logicalANDandOR)youcanstopassoonasyoufindthefirstconditionwhichsatisfiesornegatestheexpression. Forexample,supposeyouwereevaluatingalogicalORwithseveralsub-expressions,eachofwhichisverycostlytoevaluate: if(costlyTest1()||costlyTest2()||costlyTest3()){//... TheJVMcanstopevaluatingthe"costlyTest"functionsassoonasitfindsonethatreturnstrue,sincethatwillimmediatelysatisfythebooleanexpression.SoifcostlyTest1()returnstruethentheothertestswillbeskipped.Similarly: if(costlyTest1()&&costlyTest2()&&costlyTest3()){//... TheJVMcanstopevaluatingthefunctionsassoonasitfindsonethatreturnsfalse,sincethatimmediatelynegatestheexpression;soifcostlyTest1()returnsfalsethentheotherfunctionswillnotbecalled. Theserulespertainwithanylevelofnestingofbooleanexpressionsandcanbetakenadvantageoftoavoidunnecessarywork,asdemonstratedintheexamplesabove. Share Improvethisanswer Follow editedNov30'20at0:06 answeredFeb18'12at21:43 maericsmaerics 139k4040goldbadges249249silverbadges280280bronzebadges 1 Ah,Isee.Thatwassimpleenough.Thanksforyourquickandclearexplanation! – user1214845 Feb18'12at21:50 Addacomment | 2 ShortCircuit:Ifthefirstpartistruedon'tbotherevaluatingtherestoftheexpression.Samelogicappliesforfalseinthecaseof&&whichisalsoshortcircuiting Share Improvethisanswer Follow editedFeb20'12at17:56 answeredFeb18'12at21:40 CratylusCratylus 50.8k6161goldbadges198198silverbadges331331bronzebadges 9 Moreprecisely:stopevaluatingalogicalexpressionassoonastheresultiscertain. – biziclop Feb18'12at21:42 1 YoujustsaidthatJavaonlyevaluatesthefirstpartofanexpression. – Jeffrey Feb18'12at21:42 @Jeffrey:Idon'tunderstandyourcomment. – Cratylus Feb19'12at8:43 @user384706Yousaidthatifthefirstpartofanexpressionistrue,anyexpression,thenitdoesn'tevaluatetherestoftheexpression.Andthatitdoesthesamethingifthefirstpartisfalse. – Jeffrey Feb19'12at21:39 @Jeffrey:Yes.if(a&&b)ifaisfalsethentheresti.e.bisnotevaluated.Likewiseif(a||b)ifaistruethentheresti.e.bisnotevaluated.Whereistheerror? – Cratylus Feb20'12at16:20 | Show4morecomments 0 Short-circuitingtheevaluationofanexpressionmeansthatonlyapartoftheexpressionneedstobeevaluatedbeforefindingitsvalue.Forexample: a==null||a.size()==0 Ifaisnull,thea.size()==0subexpressionwon'tbeevaluated,becausethebooleanoperator||evaluatestotrueifoneofitsoperandsistrue. Similarly,forthisexpression: a!=null&&a.size()>0 Ifaisnull,thenthea.size()>0won'tbeevaluated,becausethebooleanoperator&&evaluatestofalseifoneofitsoperandsisfalse. Intheaboveexamplesthebooleanoperators&&and||aresaidtobeshort-circuit,giventhefactthatthesecondoperandmightnotbeevaluatedifthevalueofthefirstoperandisenoughtodeterminethevalueofthewholeexpression.Forcomparison,the&and|operandsaretheequivalentnon-short-circuitbooleanoperators. Share Improvethisanswer Follow editedFeb18'12at21:48 answeredFeb18'12at21:41 ÓscarLópezÓscarLópez 222k3434goldbadges297297silverbadges371371bronzebadges Addacomment | 0 ShortcircuitingisanalternativewayofusingthelogicalANDorORoperators(&or|) e.g.anonshort-circuitOR if(false|true){ } Thefirstconditionandsecondconditionarebothevaluatedeveniffalseisnottrue(whichitalwaysis). Howeveritiswaswrittenasashort-circuitOR: if(false||true){ } Thefirstconditionisonlyevaluatedsinceit'sfalse,trueisn'tevaluatedsinceit'snotrequired. Share Improvethisanswer Follow editedFeb18'12at21:50 answeredFeb18'12at21:45 JamesGoodwinJamesGoodwin 7,19033goldbadges2828silverbadges4141bronzebadges Addacomment | TheOverflowBlog Skills,notschools,areindemandamongdevelopers Podcast401:BringingAItotheedge,fromthecomfortofyourlivingroom FeaturedonMeta ProvidingaJavaScriptAPIforuserscripts Congratulationstothe59sitesthatjustleftBeta A/BtestingontheAskpage Linked 232 Whydoweusuallyuse||over|?Whatisthedifference? 32 DoesJavaevaluateremainingconditionsafterbooleanresultisknown? 2 Whyisn'ttherightsideof&&operatorevaluated? -2 InJava,whydoestheoutputofbdoesnotchangeinthecase?Isitpossiblethattheusingof"or"letsitonlyjudgethefirstcase? 1 Avoidingexceptionsbyshortcircuiting 1 behaviorofprintfunctioninsideaBooleanexpression 1 ifstatementwith3"and"(&&)operatorscauseserrorwhenrearranged -1 !=isnotfuntioningproperlyinwhileloop 41 Whatisthedifferencebetween&and&&operatorsinC# 57 DynamicquerywithORconditionsinEntityFramework Seemorelinkedquestions Related 4084 WhatarethedifferencesbetweenaHashMapandaHashtableinJava? 3682 HowdoIefficientlyiterateovereachentryinaJavaMap? 3437 Whatisthedifferencebetweenpublic,protected,package-privateandprivateinJava? 3241 WhatisaserialVersionUIDandwhyshouldIuseit? 4451 HowdoIread/convertanInputStreamintoaStringinJava? 3396 WhentouseLinkedListoverArrayListinJava? 3853 HowdoIgeneraterandomintegerswithinaspecificrangeinJava? 2318 HowdoIdeclareandinitializeanarrayinJava? 3308 HowdoIconvertaStringtoanintinJava? 3521 HowcanIcreateamemoryleakinJava? HotNetworkQuestions WhydoesVoldemortholdhiswandinthismanner? code-complianttoputsmallermainbreakerinaloadcenter? CheckingforNaNbitpatternsinC++ InMaryTighe'sPsyche,whatisthegemstonereferredtobyallusion? Howisuniformexposureachievedwhenusingaleafshutter? Whatfrequencystabilitycrystaldoweneed? Isthis"Bait-And-Switch"defencepossible? CanIpullethernetcablethrough1/2"pex? Whatisthe"stackofthirds"inchordtheory? What'sthemeaningof伐inthissentence? Estimatethehomogeneouscomponentsofapolynomialagainstitsmaximum Canyouswitchplaceswithyourmountusingbaitandswitch? Gravitationalbindingenergyasalternativetodarkmatter? Whyisn’ttheletter“G”immediatelyafter“C”inthealphabet? NthFizzBuzzNumber DoesthistweaktoJumpingruleshaveanypitfallsorproblematicinteractions? DoesthelastsceneofST:DS9"ThePassenger"involveanillegal/immoralexecution? IssuevsChildren WhatarethecolorsofthecollegesinStrixhaven:ACurriculumofChaos? Books/websiteswhichhavemotivatingstoriesofmathematiciansovercominghardshipsinlife Howtojointwotablescolumn-wisesimplyandquickly? WhataretheboxesaroundtheairportontheIVAOApproach(APP)screen? Canacongalineofcursedcreaturestransportammunitioninstantaneouslyacrosstheglobe? Patchparameterofenvironment morehotquestions lang-java Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings
延伸文章資訊
- 1JavaScript基本功修練:Day9 - 短路求值與條件運算子的應用
短路求值(Short-circuit evaluation)是指一種方法,它是指用 || 或 && 來寫比起 if 判斷式更短更簡潔的判斷式。一開始學JS時,只懂在 if else 判斷式裏面用...
- 2Short-circuit evaluation in Programming - GeeksforGeeks
Short-Circuit Evaluation: Short-circuiting is a programming concept by which the compiler skips t...
- 3JavaScript: What is short-circuit evaluation? - codeburst
What this means is that when JavaScript evaluates an OR expression, if the first operand is true,...
- 4短路求值- 維基百科,自由的百科全書
短路求值(Short-circuit evaluation,又稱最小化求值),是一種邏輯運算符的求值策略。只有當第一個運算數的值無法確定邏輯運算的結果時,才對第二個運算數進行求值。
- 5Short-circuit evaluation - Wikipedia