3.7: Conditional Expression

Introduction to Programming with C++ · LibreTexts

0%

Contents

    Text

    Size
    100%
    Theme
    Typeface
    Line length
    Spacing

    From LibreTexts, under CC BY-NC-SA 4.0, as the source states it; its equations are written in TeX, which the PDF shows typeset. This page at LibreTexts.

    3.7: Conditional Expression

    A conditional expression is a special type of selection statements.

    Structure (syntax) of a conditional expression:

    (relational statement)? x : y

    Logic of this conditional expression:

    If the relational statement is true, select the statement x, otherwise, select the statement y.

    Example

    cout << (x > y ? x : y) << endl;

    Above C++ statement will check the truth value of the relational statement x > y. If it is true, then execute the code cout<<x<<endl; If it is false, then execute the code cout<<y<<endl;

    Example

    t = (x > y ? x : y);

    Above C++ statement will check the truth value of the relational statement x > y. If it is true, then execute the code t=x; If it is false, then execute the code t=y;

    Example

    cout << (x%2==0 ? "x is even" : "x is odd");

    Above C++ statement will check the truth value of the relational statement x%2==0. If it is true, then execute the code cout<<"x is even"<<endl; If it is false, then execute the code cout<<x is odd<<endl;

    Example

    score =score +(score<=60? 10 : 5);

    Above C++ statement will check the truth value of the relational statement score<=60. If it is true, then execute the code score=score+10; If it is false, then execute the code score=score+5;



    This page titled 3.7: Conditional Expression was last modified on Wed, 24 Dec 2025 20:37:21 GMT and is shared under a CC BY-NC-SA 4.0 license and was authored, remixed, and/or curated by Jin He.