Ternary operator

From Tux
Revision as of 18:36, 23 January 2018 by Williams (talk | contribs) (Created page with "The '''ternary operator''' <code>?:</code> in C++ is the only operator that takes three operands and works similar to an if statement. It must be used carefully, and can lead...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

The ternary operator ?: in C++ is the only operator that takes three operands and works similar to an if statement. It must be used carefully, and can lead to obfuscated code.

int kids;

cin >> kids;

// using if statement
cout << "You have " << kids << "child";
if (kids != 1)
     cout << "ren";
cout << endl;

// using ternary operator
cout << "You have " << kids << "child" << (kids != 1) ? "ren" : "" << endl;