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

Top comments (0)