c# - Conditional XOR? - Stack Overflow

文章推薦指數: 80 %
投票人數:10人

There is no such thing as conditional (short-circuiting) XOR. Conditional operators are only meaningful when there's a ... Home Public Questions Tags Users Companies Collectives ExploreCollectives Teams StackOverflowforTeams –Startcollaboratingandsharingorganizationalknowledge. CreateafreeTeam WhyTeams? Teams CreatefreeTeam Collectives™onStackOverflow Findcentralized,trustedcontentandcollaboratearoundthetechnologiesyouusemost. Learnmore Teams Q&Aforwork Connectandshareknowledgewithinasinglelocationthatisstructuredandeasytosearch. Learnmore ConditionalXOR? AskQuestion Asked 11yearsago Modified 4monthsago Viewed 89ktimes 95 11 HowcomeC#doesn'thaveaconditionalXORoperator? Example: truexorfalse=true truexortrue=false falsexorfalse=false c#operatorsxorboolean-operations Share Follow editedAug12,2015at9:23 david.s 11.1k66goldbadges5252silverbadges8181bronzebadges askedJun28,2011at14:12 GiladNaamanGiladNaaman 6,0881414goldbadges4949silverbadges7979bronzebadges 15 17 Howdoes!=workasasubstitute? – PascalCuoq Jun28,2011at14:14 47 C#doeshaveanxoroperator(x^y).Ithereforedenythepremiseofthequestion.CanyouexplainwhyyoubelievedthatC#doesnothaveanxoroperator?IaminterestedtolearnwhypeoplebelievefalsethingsaboutC#. – EricLippert Jun28,2011at14:15 4 @EricLippert:Ithinkhe'sreferringtologicaloperators(&|^)vsconditionaloperators(&&||).Butyou'reright(ofcourse),thereisalogicalXOR... – BoltClock Jun28,2011at14:15 14 @BoltClock:Oh,ifthequestionis"whyistherenoshort-circuitingxoroperator?"--howcouldtherebe?With"and"ifthefirstargumentisfalseyoudon'tneedtoevaluatethesecond.With"or",ifthefirstargumentistruethenyoudon'tneedtoevaluatethesecond.Youalwaysneedtoevaluatebothargumentsforxor,sothereisnoshortcircuitingpossible. – EricLippert Jun28,2011at14:18 6 ThequestionitselfisonebettersuitedtoMicrosoft-andsothat'sadecentreasontodownvote-butifwhoeverdownvoteditdidsobecauseofthe^operator,thenyouneedtoreadwithmoreattentiontodetail,becausethequestionwasconditionalvs.logical,notsimply"whyisn'tthereanXOR". – TheEvilGreebo Jun28,2011at14:21  |  Show10morecomments 11Answers 11 Sortedby: Resettodefault Highestscore(default) Trending(recentvotescountmore) Datemodified(newestfirst) Datecreated(oldestfirst) 315 Conditionalxorshouldworklikethis: truexorfalse=true truexortrue=false falsexortrue=true falsexorfalse=false Butthisishowthe!=operatoractuallyworkswithbooltypes: (true!=false)//true (true!=true)//false (false!=true)//true (false!=false)//false Soasyousee,thenonexistent^^canbereplacedwithexisting!=. Share Follow editedMar1at15:47 StayOnTarget 10k1010goldbadges4545silverbadges6969bronzebadges answeredFeb2,2013at18:02 piotrpopiotrpo 12k77goldbadges4040silverbadges5858bronzebadges 7 56 Thisisactuallytheonlyanswerthataddressesthequestiondirectlyandcorrectly. – usr Mar22,2013at14:31 50 IamsittingherefacepalmingmyselfthatIdidn'trealize!=wouldworkforthis. – AdamMc331 Aug19,2015at15:49 2 Theansweriscorrectbutthecommentsaren't.Itdoesnotaddressthequestion,whichis"whydoesn'tC#haveaconditionalXOR?".Strictlyspeakingthisisn'talogicaloperator,it'sarelationalequalityoperator.WhiletheresultisthesameasXOR,itisinadifferentclass.ItonlycomparestoXORwhentestingtwobooleanvalues,andbothsidesoftheoperatorstillmustbeevaluated. – TheEvilGreebo May17,2017at2:22 3 @TheEvilGreebo-Whatyousayistrue;the!=operatorisnottechnicallyaconditionalXORoperator.However,thisanswereffectivelysays,"AconditionalXORoperatordoesn'texistbecausethe!=operatordoes."That'showIreadit,anyway. – Syndog May22,2017at17:33 6 IthinkprettymucheveryoneendeduptothispostactuallywantedtowriteXORonBooleans.likethereislogicalANDandORbutnothingasXOR.oratleastwedidn'trealize!=:)@TheEvilGreebo – M.kazemAkhgary Dec26,2017at13:47  |  Show2morecomments 130 InC#,conditionaloperatorsonlyexecutetheirsecondaryoperandifnecessary. SinceanXORmustbydefinitiontestbothvalues,aconditionalversionwouldbesilly. Examples: LogicalAND:&-testsbothsideseverytime. LogicalOR:|-testbothsideseverytime. ConditionalAND:&&-onlyteststhe2ndsideifthe1stsideistrue. ConditionalOR:||-onlytestthe2ndsideifthe1stsideisfalse. Share Follow editedJun28,2011at14:21 mdm 12.2k55goldbadges3333silverbadges5353bronzebadges answeredJun28,2011at14:17 TheEvilGreeboTheEvilGreebo 6,78633goldbadges2727silverbadges5454bronzebadges 9 49 AnXORoperatorwouldnotviolatetheconvention"conditionaloperatorsonlyexecutetheirsecondaryoperandifnecessary".Itwouldjustalwaysbenecessary. – NathanKovner Dec18,2015at21:57 2 ConditionalXORcouldbeaniceandelegantshortcutforsomeparticularpatterns,althoughnotsureifjustifiedenoughtoincludeitinthelanguage.AnexampleofsuchpatternswhereXORmightproveuseful,isConditionalNegation:WhenaBooleanexpressionshouldbenegatedornot,givenasecondbooleanexpression. – SalvadorGomez May5,2016at22:21 1 Haven'trespondedtothisinsometimebuttorespondtopopularcommentby@KhyadHalda:Whywouldyoueverbuildsomethingyouknowwouldneverbeused?You'dbedeliberatelywritingdeadcode. – TheEvilGreebo May15,2017at18:47 2 How,ever,wouldaconditionalXOReverbeuseful?AconditionalXORcannoteverevaluatewithoutcomparingbothsidestodeterminethattheyareorarenotequal.EventhenotionofaconditionalXORcomparingtwoboolsmuststillcheckthevalueofeachboolandtesttheequality. – TheEvilGreebo May28,2017at22:35 1 It'sassillyasaconditionaladditionoperator.Whynotmakeanotheroperatorforconditionaladdition,where(a+b)onlyevaluatesbwhenbisnecessary?JustlikewithconditionalXOR,thiswouldn'tviolatetheconventionofconditionaloperators,it'sjustthatthesecondargumentwouldalwaysbenecessary.There'snousecaseforthisever.AndI'mnotjustbeingpedanticwiththisexample--theXORoperationisessentiallya1-bitaddition. – KevinHolt May15,2019at21:16  |  Show4morecomments 32 ThereisthelogicalXORoperator:^ Documentation:C#Operatorsand^Operator Thedocumentationexplicitlystatesthat^,whenusedwithbooleanoperands,isabooleanoperator. "forthebooloperands,the^operatorcomputesthesameresultasthe inequalityoperator!=". (Andasnotedinanotheranswer,that'sexactlywhatyouwant). Youcanalsobitwise-xorintegeroperandswith^. Share Follow editedMar1at15:50 StayOnTarget 10k1010goldbadges4545silverbadges6969bronzebadges answeredJun28,2011at14:15 iceawayiceaway 1,12411goldbadge77silverbadges1212bronzebadges 4 3 Logical,notconditional.Logicaland=&,conditionaland=&&.He'saskingaboutConditional. – TheEvilGreebo Jun28,2011at14:16 3 Itisbinary,notlogical.Itassumesthatboolsareeither0or1whichisnottrueontheCLR. – usr Mar22,2013at14:29 3 sorry,thisanswerdoesnotactuallyanswerthequestionaboutCONDITIONALoperators.thisisabitopperator – NathanTregillus Apr14,2017at16:14 5 Fortherecord,thedocumentationlinkedinthisanswerexplicitlystatesthat^,whenusedwithbooleanoperands,isabooleanoperator."forthebooloperands,the^operatorcomputesthesameresultastheinequalityoperator!=".Youcanalsobitwise-xorintegeroperandswith^.C#isnotC. – 15ee8f99-57ff-4f92-890c-b56153 May17,2019at13:31 Addacomment  |  25 Justasaclarification,the^operatorworkswithbothintegraltypesandbool. SeeMSDN's^Operator(C#Reference): Binary^operatorsarepredefinedfortheintegraltypesandbool.Forintegraltypes,^computesthebitwiseexclusive-ORofitsoperands.Forbooloperands,^computesthelogicalexclusive-orofitsoperands;thatis,theresultistrueifandonlyifexactlyoneofitsoperandsistrue. Maybethedocumentationhaschangedsince2011whenthisquestionwasasked. Share Follow editedAug31,2018at21:57 jpmc26 26.3k1111goldbadges9090silverbadges140140bronzebadges answeredJun13,2016at11:50 RichardCLRichardCL 1,4171010silverbadges99bronzebadges 2 2 beenprogramminginc#alongtime,neverknewthis!thanks@RichardCL! – NathanTregillus Apr14,2017at16:19 Thisisgoodinformationbutseemsmoreappropriateasacommentoredittotheotheranswerthatmentions^andpredatesthisonebyfiveyears.Idoubtanythinghaschanged. – Chris Jul30,2019at19:49 Addacomment  |  13 AsaskedbyMarkL,Hereisthecorrectversion: FuncXOR=(X,Y)=>((!X)&&Y)||(X&&(!Y)); Hereisthetruthtable: X|Y|Result ============== 0|0|0 1|0|1 0|1|1 1|1|0 Reference: ExclusiveOR Share Follow editedJun1,2017at20:04 answeredDec29,2015at11:04 SimpleFellowSimpleFellow 3,92922goldbadges2424silverbadges3636bronzebadges 1 3 ThequestionaskedwasWHYdoesn'tC#haveaconditionalXORoperator.Thisdoesnotanswerthequestion.Astothefunctionitself:thisfunctiondoesoperateasconditionalXOR-howeverthequestionis,isitmoreefficientthanthenon-conditionalXOR?Inordertotestforexclusivetruth,XORmustconfirmthatoneandexactlyoneresultistrue.Thismeansbothsidesmustbeevaluatedandcompared.Thefunctionabovetestsbothsidesofanandconditionwhileinvertingonevalue,ataminimum.DoweknowinternallyifthisisanydifferentthanXOR? – TheEvilGreebo May31,2017at12:27 Addacomment  |  5 Ohyes,itdoes. boolb1=true; boolb2=false; boolXOR=b1^b2; Share Follow answeredJun28,2011at14:15 ArmenTsirunyanArmenTsirunyan 126k5656goldbadges316316silverbadges428428bronzebadges 7 2 Itisabinaryoperator,notalogicalone.Itassumesthatboolsareeither0or1whichisnottrueontheCLR.Sothiscodecanactuallyfailtowork. – usr Mar22,2013at14:30 8 @usr,InC#,the^operatorislogicalwhenappliedtotwoBooleanoperands.Youcommentedanawfullotthroughtheseanswers,didyoueverrunanycodetotestyourhypothesis? – MarcL. Mar28,2014at21:26 3 @MarcL.Idid:pastebin.com/U7vqpn6GPrintstrue,althoughtrue^trueissupposedtobefalse.boolisnotalwaysequalto0or1.ItisnotalogicaltypeontheCLR.Itisan8bitquantitywitharbitrarycontents.IcouldhavegeneratedverifiableILtodemonstratetheissueaswell. – usr Mar28,2014at22:42 1 @usr,okay,soyou'vemanagedtoshowthelogicaloperatorsappeartoactonBooleansbyapplyingbitwisetotheunderlying8-bitvalue--fortherecord,CreateBool(1)&CreateBool(2)willalsoyieldFalse.AndthatthisisnotsufficientiftheCLRisroughedupabit.But,asfunasthishasbeen,inwhatscenario(whereonehasn'tplainlyabusedtheCLR)doesthisdistinctionmakeanydifferencewhatsoever? – MarcL. Mar29,2014at5:23 2 WhenusingotherCLRlanguagesthanC#forexample.Irepeat:IcouldhaveusedILASMtocreateafullyverifiable,safeassemblythatdoesthis(attheILlevelabooleanvalueisjustani1,justlikeabyteis).Thisis100%definedandsafemanagedbehavior.TheCLRisnotroughed-up.;ThefirsttimeIsawthisbehaviorwaswhenusingMicrosoftPex. – usr Mar29,2014at10:11  |  Show2morecomments 4 Conditionalxordoesn'texist,butyoucanuselogicalonebecausexorisdefinedforbooleans,andallconditionalcomparisonsevaluatetobooleans. Soyoucansaysomethinglike: if((a==b)^(c==d)) { } Share Follow answeredJun28,2011at14:19 KlarkKlark 7,89233goldbadges3434silverbadges6060bronzebadges 9 1 Itisabinaryoperator,notalogicalone.Itassumesthatboolsareeither0or1whichisnottrueontheCLR.Sothiscodecanactuallyfailtowork. – usr Mar22,2013at14:30 3 @Spencevailyouprobablywerenotthinkingaboutthecasethatanon-falsebooleanmightnothaveintegerrepresentation1.Thisisalittleknownfact.Youcanendupinasituationwherethexoroftwonon-falsebooleansisstillnon-false!Thatsaidinthisparticularcodethexoroperatorisonlyeverappliedtovaluesin[0,1]sothatmycommentdoesnot(fully)apply. – usr Mar30,2015at16:09 1 @Spencevailthatisexactlythecasethatcanfail.ItispossibletocreateasafemanagedcodefunctionCreateBool(byte)thatconvertsabyteintoaboolofthesamebits.Then,CreateBool(1)^CreateBool(2)istrue,butCreateBool(1)istrueandCreateBool(2)istrueaswell!&isalsovulnerable. – usr Mar30,2015at19:27 1 Actually,IjustreportedaRyuJITbugbecausetheydidnotconsiderthispossibilityandcompiled&&asifitwere&whichisamiscompilation. – usr Mar30,2015at19:31 1 @ryanwebjacksonMaybeIshouldbutsincethevotecountsaresohigh,nobodywouldseeit...The2ndhighestansweriscorrect.It'ssimplythe!=operator:) – usr Aug31,2021at7:02  |  Show4morecomments 3 Whilethereisalogicalxoroperator^,thereisnoconditionalxoroperator.YoucanachieveaconditionalxoroftwovaluesAandBusingthefollowing: A?(!B):B Theparensarenotnecessary,butIaddedthemforclarity. AspointedoutbyTheEvilGreebo,thisevaluatesbothexpressions,butxorcannotbeshortcircuitedlikeandandor. Share Follow answeredJun28,2011at14:21 jimreedjimreed 39233silverbadges44bronzebadges 3 What'sthedifferencebetweenalogican^andaconditional^?oO – ArmenTsirunyan Jun28,2011at14:28 @ArmenTsirunyanThelogicaloperatorsperformbitwiseoperationsintypeswherethatmakessensewhiletheconditionaloperatorsoperateonbooleanvaluesandreturnabooleanresult.Consideringbooleanvalues:0101^0011hasthevalue0110. – jimreed Jun28,2011at14:42 3 no,youarecompletelywrong.therearebothtypesofXOR's(they'recalledbitwiseandlogical,respectively)inC#.Bothusethe^symbol. – ArmenTsirunyan Jun28,2011at15:10 Addacomment  |  1 youcanuse: a=b^c; justlikeinc/c++ Share Follow answeredJun28,2011at14:16 gulyangulyan 66255silverbadges1515bronzebadges Addacomment  |  0 Thereisnosuchthingasconditional(short-circuiting)XOR.Conditionaloperatorsareonlymeaningfulwhenthere'sawaytodefinitivelytellthefinaloutcomefromlookingatonlythefirstargument.XOR(andaddition)alwaysrequiretwoarguments,sothere'snowaytoshort-circuitafterthefirstargument. IfyouknowA=true,then(AXORB)=!B. IfyouknowA=false,then(AXORB)=B. Inbothcases,ifyouknowAbutnotB,thenyoudon'tknowenoughtoknow(AXORB).YoumustalwayslearnthevaluesofbothAandBinordertocalculatetheanswer.ThereisliterallynousecasewhereyoucaneverresolvetheXORwithoutbothvalues. Keepinmind,XORbydefinitionhasfourcases: falsexortrue=true truexorfalse=true truexortrue=false falsexorfalse=false Again,hopefullyit'sobviousfromtheabovethatknowingthefirstvalueisneverenoughtogettheanswerwithoutalsoknowingthesecondvalue.However,inyourquestion,youomittedthefirstcase.Ifyouinsteadwanted falseoptrue=false(orDontCare) trueopfalse=true trueoptrue=false falseopfalse=false thenyoucanindeedgetthatbyashort-circuitingconditionaloperation: A&&!B Butthat'snotanXOR. Share Follow editedMay17,2019at5:38 answeredMay15,2019at21:29 KevinHoltKevinHolt 72599silverbadges1515bronzebadges 7 I’mnotseeinganythinginthisanswerthatisn’tinatleastoneanswerabove.Idon’tseeanyindicationthatyourshort-circuitableun-xoriswhatOPwaslookingfor,sinceheacceptedananswerwhichassumeshewantedproperxor. – 15ee8f99-57ff-4f92-890c-b56153 May16,2019at1:04 MineisliterallytheonlyanswersuggestedsofarthatcanproducetheOP'srequestedtruthtablewithoutevaluatingthesecondargument. – KevinHolt May17,2019at4:56 AlsotheOPaskedwhythereisnoconditionalXOR,andwhiletheanswersabovedosaycorrectlythatit'sbecauseXORrequirestwoarguments,IMOtheanswersabovedidn'tseemtosaysufficientlyexplainWHYdoesXORactuallyneedtwoarguments.Obviouslyyoufeelotherwise,buttomeitwasapparentfromthevariouscommentsonthispagethatthebasictwo-argumentnessofXORhadn'tbeenfullyexplainedtoacompletebeginneryet. – KevinHolt May17,2019at5:21 1 Youtalkedmeintoit. – 15ee8f99-57ff-4f92-890c-b56153 May17,2019at13:37 @KevinHolt-LogicalXORismeaningfulifyouneedoneoftheconditionstobetruebutnotboth.Thatyouhavetoevaluatebothconditionsdoesn'tmatter.Theshortcircuitthingisalowleveldetailthatyouonlyhavetoworryaboutwhendealingwithperformancecriticalcode(controlflowisslow).I'dbemoreconcernedwithwhat'exclusiveor'issupposedtomeanwhenmakingalogicaloperatoroutofit.Namely,haveitoperatelikethebitwiseversion(liketheotheroperators),ormakeitanorthat'sexclusive(asmanyconditionsasyouwant,butonlyonecanbetrue). – Thorham Oct4,2019at13:35  |  Show2morecomments -3 Thisquestionhasbeenaffectivelyanswered,butIcameacrossadifferentsituation.It'struethatthereisnoneedforaconditionalXOR.It'salsotruethatthe^operatorcanbeused.However,ifyouneedtoonlytestthe"true||false"statusoftheoperandsthen^canleadtotrouble.Forexample: voidTurn(intleft,intright) { if(left^right) { //success...turnthecarleftorright... } else { //error...noturnorbothleftANDrightareset... } } Inthisexample,ifleftissetto10(0xa)andrightissetto5(0x5)the"success"branchisentered.Forthis(simplisticifsilly)example,thiswouldresultinabugsinceyoushouldn'tturnleftANDrightatthesametime.WhatIgatheredfromthequestionerisnotthatheactuallywantedaconditional,butasimplewaytoperformthetrue/falseonthevaluesaspassedtothexor. Amacrocoulddothetrick: #definemy_xor(a,b)(((a)?1:0)^((b)?1:0)) FeelfreetoslapmearoundifI'moffthemark:o) Ireadjimreed'sanswerbelowafterIpostedthis(badYapdog!)andhisisactuallysimpler.ItwouldworkandIhaveabsolutelynoideawhyhisanswerwasvoteddown... Share Follow editedAug21,2012at1:26 answeredAug20,2012at23:08 YapDogYapDog 15311silverbadge44bronzebadges 1 3 ThisisaC#question,notC/C++.ifrequiresaBooleanexpression,itwon'tevencompilewithanint. – MarcL. Mar28,2014at21:24 Addacomment  |  YourAnswer ThanksforcontributingananswertoStackOverflow!Pleasebesuretoanswerthequestion.Providedetailsandshareyourresearch!Butavoid…Askingforhelp,clarification,orrespondingtootheranswers.Makingstatementsbasedonopinion;backthemupwithreferencesorpersonalexperience.Tolearnmore,seeourtipsonwritinggreatanswers. Draftsaved Draftdiscarded Signuporlogin SignupusingGoogle SignupusingFacebook SignupusingEmailandPassword Submit Postasaguest Name Email Required,butnevershown PostYourAnswer Discard Byclicking“PostYourAnswer”,youagreetoourtermsofservice,privacypolicyandcookiepolicy Nottheansweryou'relookingfor?Browseotherquestionstaggedc#operatorsxorboolean-operationsoraskyourownquestion. TheOverflowBlog HowStackOverflowislevelingupitsunittestinggame Developersvsthedifficultybomb(Ep.459) FeaturedonMeta Testingnewtrafficmanagementtool Duplicatedvotesarebeingcleanedup Trending:Anewanswersortingoption Updatedbuttonstylingforvotearrows:currentlyinA/Btesting Related 1118 Howtoescapebraces(curlybrackets)inaformatstringin.NET 7358 DoesPythonhaveaternaryconditionaloperator? 3264 Caseinsensitive'Contains(string)' 1522 Istherea"nullcoalescing"operatorinJavaScript? 290 Creatinga"logicalexclusiveor"operatorinJava 351 LogicalXORoperatorinC++? 1916 HowdoIremedy"Thebreakpointwillnotcurrentlybehit.Nosymbolshavebeenloadedforthisdocument."warning? 1516 HowtoSortaListbyapropertyintheobject 4934 Reference—WhatdoesthissymbolmeaninPHP? 2267 Whatdoesthe??!??!operatordoinC? HotNetworkQuestions CanaU.S.statebringactionbeforetheSupremeCourtagainstanotherstateforequalrightsofitsowncitizenswhentheyvisittheotherstate? ReligiouscharactersintheMCU Arebriftersmeanttospin/slideonimpact,bythechoiceofalowattachment-bolttorque? DrawtheUSAflag Bashfunctioninsidefunction:Howtointerpolatecertainvariablesfromouterfunction Doesawatercloset(toiletstall)requireanelectricaloutlet? Can"RighttoRepair"laws(orotherlaws)requireacompanytoopensourcetheirproprietaryfirmware? Howareweatherballoonsdifferentfrom"regular"biglatexballoons? Whyisitassumedthatspaceflightshavetobesafe? Is86%ofthefoodfedtolivestockunfitforhumanconsumption,andismostofitbyproductsofcropsgrownforhumanconsumption? Problemmodellingasimpleshapeandthenapplyingsubdivisionsurfacemodifier Whatisthemeaningof"reflecting"inthiscontext? Whatadvantages/disadvantageswouldHomoErectushaveina19thCenturymilitaryconflict? Quantumsupercomputersinorbit? Isthedefinitionofametertautological? Difficultyforafiremantoholdahose,whichejectslargeamountsofwateratahighvelocity I’maforeignerwithanexpiredpassportwhichhasmyvalidvisa.CanItakeadomesticflightintheUSifIdon’thaveanyotherID? Managermakingmeworkextrapost-notice(UK—Scotland) WhichoutputfilefromCASTEPaftergeometryoptimizationislikewiththeCONTCARfromVASP? Howtomakeflatsurfaceslookflatwithsmoothshading? DevelopmentofOldNorse2ndand3rdpersonsg.(presentindicative)formsof"tobe" HowdoIprovethattheadditionofnaturalnumbers,asdefinedbyPeano,isunique? Visualizeacontinuousvariableagainstabinaryvariable Howdoesheatradiateawayfromconcavesurface? morehotquestions Questionfeed SubscribetoRSS Questionfeed TosubscribetothisRSSfeed,copyandpastethisURLintoyourRSSreader. lang-cs Yourprivacy Byclicking“Acceptallcookies”,youagreeStackExchangecanstorecookiesonyourdeviceanddiscloseinformationinaccordancewithourCookiePolicy. Acceptallcookies Customizesettings  



請為這篇文章評分?