Conditional or Ternary Operator (?:) in C/C++ - GeeksforGeeks
文章推薦指數: 80 %
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
延伸文章資訊
- 1Ternary Operator in C Explained - freeCodeCamp
Programmers use the ternary operator for decision making in place of longer if and else condition...
- 2條件運算子- JavaScript
JavaScript Demo: Expressions - Conditional operator. xxxxxxxxxx. 1. function getFee(isMember) {. ...
- 3What is a Ternary Operator? - Computer Hope
The ternary operator is an operator that exists in some programming languages, which takes three ...
- 4?: operator - C# reference | Microsoft Docs
Learn about the C# ternary conditional operator that returns the result of one of the two express...
- 5JavaScript Ternary Operator (with Examples) - Programiz
What is a Ternary operator? ... A ternary operator evaluates a condition and executes a block of ...