4

Possible Duplicate:
Benefits of using the conditional ?: (ternary) operator

hi, I'm viewing this freesource library and I saw this weird - at least for me - syntax

*currFrame = ( ( diff >= differenceThreshold ) || ( diff <= differenceThresholdNeg ) ) ? (byte) 255 : (byte) 0;

currFrame is of type byte

diff, differenceThreshold and differenceThresholdNeg are of type Int.

What does the question mark do ? , what is this weird assign sentence suppose to mean ?

Thanks in advance

Community
  • 1
  • 1
musaab
  • 43
  • 1
  • 4

7 Answers7

8

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. Following is the syntax for the conditional operator.

condition ? first_expression : second_expression;

C# reference: http://msdn.microsoft.com/en-us/library/ty67wk28.aspx

In your case currFrame will be assigned a value of 255 if ( diff >= differenceThreshold ) || ( diff <= differenceThresholdNeg ) is true, otherwise value 0 will be assigned.

Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
7

this is the same as

if(( diff >= differenceThreshold ) || ( diff <= differenceThresholdNeg ) )
     currFrame = (byte) 255
else
    currFrame = (byte) 0
JAiro
  • 5,914
  • 2
  • 22
  • 21
4

It is the conditional operator.

Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
  • 2
    Its *name* is the conditional operator though. It happens to be the only ternary operator currently in C#, but it's worth calling it by its name rather than just identifying it by the number of operands, IMO. – Jon Skeet Feb 28 '11 at 14:43
  • 2
    It is *a* ternary operator. It's specifically the conditional operator. Whilst, at present, C# exposes only a single ternary operator, you wouldn't go around referring to `+` as "the binary operator" – Damien_The_Unbeliever Feb 28 '11 at 14:43
  • I'll bow to peer pressure and put conditional. – Yuriy Faktorovich Feb 28 '11 at 14:45
3

?: Operator (C# Reference):

The conditional operator (?:) returns one of two values depending on the value of a Boolean expression. The conditional operator is of the form

condition ? first_expression : second_expression;
CD..
  • 72,281
  • 25
  • 154
  • 163
1

'?:' is a conditional operator, you can read about it here: http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.80).aspx

tpeczek
  • 23,867
  • 3
  • 74
  • 77
0

This is a ternary operator (see MSDN). It follows the following syntax:

result = condition ? result_if_condition_true : result_if_condition_false
Matthew Abbott
  • 60,571
  • 9
  • 104
  • 129
0
if ( diff >= differenceThreshold ) || ( diff <= differenceThresholdNeg ) ) 
*currFrame = (byte) 255;
else *currFrame =  (byte) 0;
Erix
  • 7,059
  • 2
  • 35
  • 61