Thursday, August 25, 2011

Conditional Operator: ? : and its use on C++

The conditional operator is the only C++ ternary operator (working on three values). Other operators you have seen are called binary operators (working on two values). It is that is part of the syntax for a basic conditional expression in several programming languages. It is commonly referred to as the conditional operator or inline if (iif).
?: is used as follows:
condition ? value if true : value if false

The condition is evaluated true or false as a Boolean expression. On the basis of the evaluation of the Boolean condition, the entire expression returns value if true if condition is true, but value if false otherwise. Usually the two sub-expressions value if true and value if false must have the same type, which determines the type of the whole expression. The importance of this type-checking lies in the operator's most common use—in conditional assignment statements.


Conditional Operator Implementation on C++:
#include <iostream>
using namespace std;
int main() {
   int i = 1, j = 2;
   cout << ( i > j ? i : j ) << " is greater." << endl;
}

0 comments em “Conditional Operator: ? : and its use on C++”

Post a Comment

Give your valuable Comment...

 

Programming, Data Structures & Algorithms Copyright © 2011 -- Template created by JAK -- Powered by Blogger