C++ Learning Resource Network!

 
 
 
 
 
 C++ Tutorials  >  Variables, Construct & Looping  >  Conditional Operators
 

Consider the following if..else statements:

if(iNum1 > iNum2)
{
iMax = iNum1;
}
else
{
iMax = iNum2;
}


In the above program code, iMax is assigned the value iNum1 if the test expression is true, and is assigned the value iNum2 if the test expression is false.

The above program code can be modified using the conditional operator in the following way:

iMax = (iNum1 > iNum2) ? iNum1 : iNum2;

The ?: operator is called the conditional(or the ternary) operator and takes the form, v = Exp1 ? Exp2 : Exp3;

Where Exp1, Exp2 and Exp3 are expressions. Exp1 is evaluated. If it is true, the value of Exp2 is assigned to v, and if it is false, then the value of Exp3 is assigned to v. For example, in the statement

iVar1 = 10;
iVar2 = (iVar1 > 9) ? 30 : 40;


iVar2 will be assigned the value 30. If iVar1 is less than of equal to 9, then iVar2 would receive the value 40.

 

| Bookmark This Site |   | Links |   | Search |   | Submit |   | Contact |

  Copyright 2008 - 3008  CppTutor.com All rights reserved.