Short-circuit evaluation in Programming - GeeksforGeeks

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

Short-Circuit Evaluation: Short-circuiting is a programming concept by which the compiler skips the execution or evaluation of some sub- ... Skiptocontent TutorialsPracticeDS&Algo.MustDoQuestionsDSATopic-wiseDSACompany-wiseAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesISROCSISROCSSolvedPapersISROCSOriginalPapersandOfficialKeysISROCSSyllabusforScientist/EngineerExamUGCNETCSUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsGeekontheTopCareersInternshipJobsApplyforJobsPostaJobCourses ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantri HomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningWebDevelopmentPuzzlesProjectIdeasGFGSchool RelatedArticles ▲RelatedArticlesstd::sort()inC++STLArraysinC/C++WhatisMemoryLeak?Howcanweavoid?DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()BitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++ConvertingStringstoNumbersinC/C++MultidimensionalArraysinC/C++LeftShiftandRightShiftOperatorsinC/C++rand()andsrand()inC/C++DifferentmethodstoreverseastringinC/C++CommandlineargumentsinC/C++SubstringinC++CLanguageIntroductionEnumeration(orenum)inCfork()inCForVersusWhileFunctionPointerinCstd::stringclassinC++DataTypesinCStructuresinCPointertoanArray|ArrayPointerINT_MAXandINT_MINinC/C++andApplicationsTakingStringinputwithspaceinC(4DifferentMethods)MemoryLayoutofCProgramsStaticVariablesinCModuloOperator(%)inC/C++withExamplesPowerFunctioninC/C++FunctionsinC/C++PointersinCandC++|Set1(Introduction,ArithmeticandArray)TableofContentsstd::sort()inC++STLArraysinC/C++WhatisMemoryLeak?Howcanweavoid?DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()BitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++ConvertingStringstoNumbersinC/C++MultidimensionalArraysinC/C++LeftShiftandRightShiftOperatorsinC/C++rand()andsrand()inC/C++DifferentmethodstoreverseastringinC/C++CommandlineargumentsinC/C++SubstringinC++CLanguageIntroductionEnumeration(orenum)inCfork()inCForVersusWhileFunctionPointerinCstd::stringclassinC++DataTypesinCStructuresinCPointertoanArray|ArrayPointerINT_MAXandINT_MINinC/C++andApplicationsTakingStringinputwithspaceinC(4DifferentMethods)MemoryLayoutofCProgramsStaticVariablesinCModuloOperator(%)inC/C++withExamplesPowerFunctioninC/C++FunctionsinC/C++PointersinCandC++|Set1(Introduction,ArithmeticandArray)ImproveArticle SaveArticle LikeArticle Short-circuitevaluationinProgrammingLastUpdated: 22Jun,2021Short-CircuitEvaluation:Short-circuitingisaprogrammingconceptbywhichthecompilerskipstheexecutionorevaluationofsomesub-expressionsinalogicalexpression.Thecompilerstopsevaluatingthefurthersub-expressionsassoonasthevalueoftheexpressionisdetermined.Belowisanexampleofthesame:Takeastep-upfromthose"HelloWorld"programs.LearntoimplementdatastructureslikeHeap,Stacks,LinkedListandmanymore!CheckoutourDataStructuresinCcoursetostartlearningtoday.C++if(a==b||c==d||e==f){    //do_something}Explanation:Intheaboveexpression,Iftheexpressiona==bistrue,thenc==dande==fareneverevaluatedatallbecausetheexpression’sresulthasalreadybeendetermined.Similarly,ifthelogicalAND(&&)operatorinsteadoflogicalOR(||)andtheexpressiona==bisfalse,thecompilerwillskipevaluatingothersub-expressions.Example1:C++//Cprogramtoillustratetheconcept//ofshortcircuiting#include  //DriverCodeintmain(){    intx=1;      if(x||++x){        printf("%d",x);    }      return0;}Output1Explanation:IntheaboveCprogram,insidetheifstatement,thevalueofthefirstsub-expressioni.e.,xis1(whichmeanstrueinboolean),sothevalueofthesecondsub-expressiondoesnotaffectthevalueoftheexpressionandhencethecompilerskipscheckingit.Sothevalueofxisnotincremented.Example2:C//Cprogramtoillustratetheconcept//ofshortcircuiting#include  //DriverCodeintmain(){    inta=10;    intb=-1;      //Hereb==-1isnotevaluatedas    //a!=10isfalse    if(a!=10&&b==-1){        printf("Iwon'tbeprinted!\n");    }    else{        printf("Hello,elseblockisprinted");    }      return0;}OutputHello,elseblockisprintedExplanation:Theaboveprogramprintstheoutputoftheelseblockbecausethefirstconditionisfalsewhichissufficienttodeterminetheexpression’svalue,sothesecondconditionisnotevaluated.Example3:BelowistheCprogramtocalculatethesquareroottodemonstratetheconceptofshort-circuitevaluation:C//Cprogramtoillustratetheconcept//ofshortcircuiting#include#include  //Functiontocalculate thesquarerootintcalculate_sqrt(inti){    printf("Sqrtof%d:%.2f\n",           i,sqrt(i));      returni;}  //DriverCodeintmain(){    inta=15;      //Heresinceais10,calculate_sqrt    //functionwillbecalled    if(a>=10&&calculate_sqrt(a)){        printf("Iwillbeprinted!\n");    }      return0;}OutputSqrtof15:3.87 Iwillbeprinted!Explanation:Intheaboveprogramifthenumberislessthan10thenthesquarerootisnotperformed.Duetothistheerroraregettingavoidedforthenegativenumberaswell.Applications:Theconceptofshort-circuitingcanbehelpfulinmanyscenarios.Someofthemarelistedbelow:Avoidingunexpectedbehavior:Itcanbeusedtoavoidunexpectedbehaviorduetothesecondargument.ForExample:considerthebelowcodesnippet:C//Cprogramtoillustratetheconcept//ofshortcircuiting#include  //DriverCodeintmain(){    floatnr=5,dr=0;    dr&&printf("a/b=%.2f",nr/dr);}Output Explanation:Astheexpression(nr/dr)givesruntimeerrorsbutduetoaddingtheexpressiondr&&withtheoperation,theerroravoidedasthevalueofdris0whichexcludesthecomputationof(nr/dr).AvoidingExpensiveComputation:Itcanbehelpfulinavoidingexpensivecomputationswhicharerequiredtobeexecutedonlyunderspecificconditions.Belowisthecodesnippettoillustratethesame:Cinta=0;  //myfunc(b)willnotbecalledif(a!=0&&myfunc(b)){    //do_something();}Examples:Intheaboveexample,ifitisrequiredtodoanexpensiveoperationusingthemyfunc()forthevalue0,thentheexpensiveoperationforthenon-zerovaluescanbeavoidedbyusingthisconcept.ThiscanalsobeusedinfilehandlingtoavoidtheexpensivetaskofgettingafilereadyeverytimeifthefileisalreadyinareadystateasisFileReady()||getFileReady() AdvantagesOfShort-CircuitEvaluation:Itcanbehelpfulinavoidingcomputationallyexpensivetasksundercertaincircumstances.Itprovidesacheckforthefirstargumentwithoutwhichthesecondargumentmayresultinaruntimeerror.DisadvantagesOfShort-CircuitEvaluation:Itcancauseunexpectedbehaviorifnotusedproperly.Foranyfunctioninthecodesnippetthatdoessomekindofallocationofsystemresources/memoryallocation,wemaygetunexpectedbehavior.Codeexecutionbecomeslessefficientwithshort-circuitedexecutionpathsbecauseinsomecompilersthenewchecksforshort-circuitsareextraexecutioncyclesinthemselves.MyPersonalNotes arrow_drop_upSave LikePreviousIntegralsNext Introductionto3DPlottingwithMatplotlibRecommendedArticlesPage:11,Jun1014,Aug1010,Jan1415,Jul1518,Apr1629,Aug1623,Oct1613,Dec1611,Feb1429,Oct1713,May1904,Sep1813,Oct1804,Jan1910,Jan1908,Feb1901,Mar1925,Nov1927,Dec1914,Feb2014,Feb2014,Feb2022,Apr2009,May20ArticleContributedBy:Farzam@FarzamVotefordifficultyEasy Normal Medium Hard ExpertArticleTags:CBasicsCLanguageCProgramsReportIssueWritingcodeincomment? Pleaseuseide.geeksforgeeks.org, generatelinkandsharethelinkhere. LoadCommentsWhat'sNewViewDetailsViewDetailsViewDetailsMostpopularinCLanguageSwitchStatementinC/C++ExceptionHandlinginC++TCPServer-ClientimplementationinCDifferencebetweenCandC++OperatorsinC/C++MostvisitedinCProgramsStringsinCArrowoperator->inC/C++withExamplesUDPServer-ClientimplementationinCBasicsofFileHandlinginCHeaderfilesinC/C++anditsuses× Weusecookiestoensureyouhavethebestbrowsingexperienceonourwebsite.Byusingoursite,you acknowledgethatyouhavereadandunderstoodour CookiePolicy& PrivacyPolicy GotIt! StartYourCodingJourneyNow!Login Register



請為這篇文章評分?