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
  • 44,908
  • 7
  • 86
  • 126
7

this is the same as

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

It is the conditional operator.

Yuriy Faktorovich
  • 64,850
  • 14
  • 101
  • 138
  • 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..
  • 68,981
  • 24
  • 147
  • 156
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,447
  • 3
  • 72
  • 76
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
  • 59,075
  • 9
  • 102
  • 128
0
if ( diff >= differenceThreshold ) || ( diff <= differenceThresholdNeg ) ) 
*currFrame = (byte) 255;
else *currFrame =  (byte) 0;
Erix
  • 6,857
  • 2
  • 33
  • 60