Electron microscopy
 
? Operator in DM
- Practical Electron Microscopy and Database -
- An Online Book -
Microanalysis | EM Book                                                                                   http://www.globalsino.com/EM/        


=================================================================================

 

One of the most fascinating operators in C++ is the ?. The ? here is called a ternary operator because it requires three operands. The ? operator can be used to replace if-else statements as shown in Table 1118a.

Table 1118a. Comparison of applications between ? operator and if-else statements.

? operator
if-else statement

Expression1 ? Expression2 : Expression3
----------------------------------
The Expression1, Expression2 and Expression3 are expressions. The value of a ? expression is determined in this way: Expression1 is evaluated. If it is true, then Expression2 is evaluated and becomes the value of the entire ? expression. If Expression1 is false, then Expression3 is evaluated and then its value becomes the value of the expression.

if (condition)
variable = expression1;
else
variable = expression2;
----------------------------------
The value assigned to variable depends on the outcome of the condition controlling the if

Comparison of applications between ? operator and if-else statements 
Script file
Here, x will be assigned the value 0 until round(random() is larger than or equal to 0.5.
Comparison of applications between ? operator and if-else statements 
Script file
Here, x will aslo be assigned the value 0 until round(random() is larger than or equal to 0.5.

In the arithmetic mask form "xyz1 ? xyz2 : xyz3" in the example, xyz1 is always evaluated. If xyz1 evaluates to true (not 0) xyz2 is evaluated and its result used as the value of the whole expression. Otherwise, xyz3 is evaluated and its result used as the value of the whole expression.

Table 1118b. More examples of applications of the ? operator.

Script
Note

Script file

This script divides two numbers, but will not allow a division by zero.

If j is non-zero, then i is divided by j, and the outcome is assigned to EMresult. Otherwise, the div_zero( ) error handler is called and zero is assigned to EMresult.

 

 

 

 

 

 

=================================================================================