DEV Community

dinhluanbmt
dinhluanbmt

Posted on

C++, Conditional (ternary) operator

When the conditions and expressions are simple and concise, the conditional operator is extremely useful. It can reduce multiple lines of if-else conditions to a single line, making the code more compact and readable.
some examples:

void conditional_operator_example(int a, int b, string str1, string str2) {    
    //Ensure i >= 0    
    int i = (a - 2 > 0) ? a - 2 : 0;
    cout << "i : " << i << endl;

    //Grade base on mark
    int mark = b;
    string result = (mark >= 5) ? "Pass" : "Fail";
    cout << "Result : " << result << endl;

    // Get the longer string
    string& long_str = str1.length() > str2.length() ? str1 : str2;
    cout << " longer str : " << long_str << endl;

    //Check if the two numbers have the same sign (both positive or both negative)    
    bool is_sameSign = ((a >= 0) == (b >= 0)) ? true : false;
    cout << "Same Sign : " <<boolalpha<< is_sameSign << endl;
}
Enter fullscreen mode Exit fullscreen mode

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs