Difference between revisions of "Ternary operator"

From Tux
Jump to: navigation, search
(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...")
 
 
(One intermediate revision by the same user not shown)
Line 1: Line 1:
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 to obfuscated code.
+
The '''ternary operator''' <code>?:</code> in C++ is the only operator that takes three operands and works similar to an <code>if</code> statement.  It must be used carefully, and can lead to obfuscated code.
 +
 
 +
<code> a ? b : c </code> is equivalent to <code>if (a) b else c</code>.
  
 
<source lang="cpp">
 
<source lang="cpp">
Line 7: Line 9:
  
 
// using if statement
 
// using if statement
cout << "You have " << kids << "child";
+
cout << "You have " << kids << " child";
 
if (kids != 1)
 
if (kids != 1)
 
     cout << "ren";
 
     cout << "ren";
Line 13: Line 15:
  
 
// using ternary operator
 
// using ternary operator
cout << "You have " << kids << "child" << (kids != 1) ? "ren" : "" << endl;
+
cout << "You have " << kids << " child" << ((kids != 1) ? "ren" : "") << endl;
 
</source>
 
</source>
 +
 +
The above code uses the ternary operator to accurately output 0 children, 1 child, 2 children, 3 children, etc.

Latest revision as of 18:39, 23 January 2018

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.

a ? b : c is equivalent to if (a) b else c.

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;

The above code uses the ternary operator to accurately output 0 children, 1 child, 2 children, 3 children, etc.