Conditional or Ternary Operator (?:) in C/C++ - GeeksforGeeks

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

The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the ... Skiptocontent CoursesForWorkingProfessionalsLIVEDSALiveClassesSystemDesignJavaBackendDevelopmentFullStackLIVEExploreMoreSelf-PacedDSA-SelfPacedSDETheoryAllDevelopmentCoursesExploreMoreForStudentsLIVECompetitiveProgrammingGATELiveCourse2023DataScienceExploreMoreSelf-PacedDSA-SelfPacedCIPJAVA/Python/C++ExploreMoreSchoolCoursesSchoolGuidePythonProgrammingLearnToMakeAppsExploremoreAllCoursesTutorialsAlgorithmsAnalysisofAlgorithmsAsymptoticAnalysisWorst,AverageandBestCasesAsymptoticNotationsLittleoandlittleomeganotationsLowerandUpperBoundTheoryAnalysisofLoopsSolvingRecurrencesAmortizedAnalysisWhatdoes'SpaceComplexity'mean?Pseudo-polynomialAlgorithmsPolynomialTimeApproximationSchemeATimeComplexityQuestionSearchingAlgorithmsSortingAlgorithmsGraphAlgorithmsPatternSearchingGeometricAlgorithmsMathematicalBitwiseAlgorithmsRandomizedAlgorithmsGreedyAlgorithmsDynamicProgrammingDivideandConquerBacktrackingBranchandBoundAllAlgorithmsDataStructuresArraysLinkedListStackQueueBinaryTreeBinarySearchTreeHeapHashingGraphAdvancedDataStructureMatrixStringsAllDataStructuresInterviewCornerCompanyPreparationTopTopicsPracticeCompanyQuestionsInterviewExperiencesExperiencedInterviewsInternshipInterviewsCompetititveProgrammingDesignPatternsSystemDesignTutorialMultipleChoiceQuizzesLanguagesCC++JavaPythonC#JavaScriptjQuerySQLPHPScalaPerlGoLanguageHTMLCSSKotlinML&DataScienceMachineLearningDataScienceCSSubjectsMathematicsOperatingSystemDBMSComputerNetworksComputerOrganizationandArchitectureTheoryofComputationCompilerDesignDigitalLogicSoftwareEngineeringGATEGATEComputerScienceNotesLastMinuteNotesGATECSSolvedPapersGATECSOriginalPapersandOfficialKeysGATE2021DatesGATECS2021SyllabusImportantTopicsforGATECSWebTechnologiesHTMLCSSJavaScriptAngularJSReactJSNodeJSBootstrapjQueryPHPSoftwareDesignsSoftwareDesignPatternsSystemDesignTutorialSchoolLearningSchoolProgrammingMathematicsNumberSystemAlgebraTrigonometryStatisticsProbabilityGeometryMensurationCalculusMathsNotes(Class8-12)Class8NotesClass9NotesClass10NotesClass11NotesClass12NotesNCERTSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionRDSharmaSolutionsClass8MathsSolutionClass9MathsSolutionClass10MathsSolutionClass11MathsSolutionClass12MathsSolutionPhysicsNotes(Class8-11)Class8NotesClass9NotesClass10NotesClass11NotesChemistryNotesClass8NotesClass9NotesClass10NotesCSExams/PSUsISROISROCSOriginalPapersandOfficialKeysISROCSSolvedPapersISROCSSyllabusforScientist/EngineerExamUGCNETUGCNETCSNotesPaperIIUGCNETCSNotesPaperIIIUGCNETCSSolvedPapersStudentCampusAmbassadorProgramSchoolAmbassadorProgramProjectGeekoftheMonthCampusGeekoftheMonthPlacementCourseCompetititveProgrammingTestimonialsStudentChapterGeekontheTopInternshipCareersJobsApplyforJobsPostaJobHirewithUsKnowaboutJobathonJobathonPracticeAllDSAProblemsProblemoftheDayInterviewSeries:WeeklyContestsBi-WizardCoding:SchoolContestsContestsandEventsPracticeSDESheetCuratedDSAListsTop50ArrayProblemsTop50StringProblemsTop50TreeProblemsTop50GraphProblemsTop50DPProblems ComewritearticlesforusandgetfeaturedLearnandcodewiththebestindustryexpertsGetaccesstoad-freecontent,doubtassistanceandmore!ComeandfindyourdreamjobwithusGeeksDigestQuizzesGeeksCampusGblogArticlesIDECampusMantriHomeSavedVideosCoursesGBlogPuzzlesWhat'sNew? ChangeLanguage DataStructuresAlgorithmsInterviewPreparationTopic-wisePracticeC++JavaPythonCompetitiveProgrammingMachineLearningHTMLSDESheetPuzzlesGFGSchoolProjects CompleteInterviewPreparationat20%off|Usecode:PREPAREKAROCheckNow RelatedArticles ▲RelatedArticlesNvidiaInterview|Set1NvidiaInterview|Set3(OnCampus)NvidiaInterviewExperience|Set4(OnCampus)NvidiaInterviewExperience|Set5ComputeaverageoftwonumberswithoutoverflowImplementingternaryoperatorwithoutanyconditionalstatementConditionalorTernaryOperator(?:)inC/C++AcommaoperatorquestionResultofcommaoperatorasl-valueinCandC++OrderofoperandsforlogicaloperatorsIncrement(Decrement)operatorsrequireL-valueExpressionPrecedenceofpostfix++andprefix++inC/C++ModulusonNegativeNumbersC/C++TernaryOperator–SomeInterestingObservationsPre-increment(orpre-decrement)WithReferencetoL-valueinC++newanddeleteOperatorsinC++ForDynamicMemorymalloc()vsnewdeleteandfree()inC++deletekeywordinC++NvidiaInterview|Set2(OnCampusforR&DTeam,Pune)ArraysinC/C++DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()std::sort()inC++STLBitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++WhatisMemoryLeak?Howcanweavoid?ConvertingStringstoNumbersinC/C++MultidimensionalArraysinC/C++LeftShiftandRightShiftOperatorsinC/C++rand()andsrand()inC/C++NvidiaInterview|Set1NvidiaInterview|Set3(OnCampus)NvidiaInterviewExperience|Set4(OnCampus)NvidiaInterviewExperience|Set5ComputeaverageoftwonumberswithoutoverflowImplementingternaryoperatorwithoutanyconditionalstatementConditionalorTernaryOperator(?:)inC/C++AcommaoperatorquestionResultofcommaoperatorasl-valueinCandC++OrderofoperandsforlogicaloperatorsIncrement(Decrement)operatorsrequireL-valueExpressionPrecedenceofpostfix++andprefix++inC/C++ModulusonNegativeNumbersC/C++TernaryOperator–SomeInterestingObservationsPre-increment(orpre-decrement)WithReferencetoL-valueinC++newanddeleteOperatorsinC++ForDynamicMemorymalloc()vsnewdeleteandfree()inC++deletekeywordinC++NvidiaInterview|Set2(OnCampusforR&DTeam,Pune)ArraysinC/C++DynamicMemoryAllocationinCusingmalloc(),calloc(),free()andrealloc()std::sort()inC++STLBitwiseOperatorsinC/C++CoreDump(Segmentationfault)inC/C++WhatisMemoryLeak?Howcanweavoid?ConvertingStringstoNumbersinC/C++MultidimensionalArraysinC/C++LeftShiftandRightShiftOperatorsinC/C++rand()andsrand()inC/C++ConditionalorTernaryOperator(?:)inC/C++ViewDiscussion ImproveArticle SaveArticle LikeArticle DifficultyLevel: EasyLastUpdated: 23Jun,2022Theconditionaloperatoriskindofsimilartotheif-elsestatementasitdoesfollowthesamealgorithmasofif-elsestatementbuttheconditionaloperatortakeslessspaceandhelpstowritetheif-elsestatementsintheshortestwaypossible.Syntax: Theconditionaloperatorisoftheformvariable=Expression1?Expression2:Expression3Orthesyntaxwillalsobeinthisformvariable=(condition)?Expression2:Expression3Orsyntaxwillalsobeinthisform(condition)?(variable=Expression2):(variable=Expression3)Itcanbevisualizedintoif-elsestatementas:  if(Expression1) { variable=Expression2; } else { variable=Expression3; }SincetheConditionalOperator‘?:’takesthreeoperandstowork,hencetheyarealsocalledternaryoperators.Working: Here,Expression1istheconditiontobeevaluated.Ifthecondition(Expression1)isTruethenExpression2willbeexecutedandtheresultwillbereturned.Otherwise,ifthecondition(Expression1)isfalsethenExpression3willbeexecutedandtheresultwillbereturned.Example1:ProgramtoStorethegreatestofthetwoNumber. C//Cprogramtofindlargestamongtwo//numbersusingternaryoperator #include intmain(){    intm=5,n=4;     (m>n)?printf("misgreaterthannthatis%d>%d",                     m,n)            :printf("nisgreaterthanmthatis%d>%d",                     n,m);     return0;}C++//C++programtofindlargestamongtwo//numbersusingternaryoperator #includeusingnamespacestd; intmain(){    //variabledeclaration    intn1=5,n2=10,max;     //Largestamongn1andn2    max=(n1>n2)?n1:n2;     //Printthelargestnumber    cout<4Example2:Programtocheckwhetherayearisleapyearornot.C//Cprogramtocheckwhetherayearisleapyearornot//usingternaryoperator #include intmain(){    intyr=1900;     (yr%4==0)?(yr%100!=0?printf("Theyear%disaleapyear",yr)     :(yr%400==0?printf("Theyear%disaleapyear",yr)         :printf("Theyear%disnotaleapyear",yr)))             :printf("Theyear%disnotaleapyear",yr);    return0;} //ThiscodeiscontributedbySusobhanAKhuliC++//C++programtocheckwhetherayearisleapyearornot//usingternaryoperator #includeusingnamespacestd; intmain(){    intyr=1900;     (yr%4==0)?(yr%100!=0?cout<



請為這篇文章評分?