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

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay