I am working on a project, designed by someone else. I came across the following operation. I have no idea what it is doing. It seems to be returning 1.
Anyone care to elaborate? Thank you!
( 7 > 8?2:1)
I am working on a project, designed by someone else. I came across the following operation. I have no idea what it is doing. It seems to be returning 1.
Anyone care to elaborate? Thank you!
( 7 > 8?2:1)
You're looking at the Ternary Operator.
It consists of (condition) ? (expression1) : (expression2)
. The entire expression will evaluate to (expression1)
if (condition)
is true, and (expression2)
if (condition)
is false.
var i = (7 > 8 ? 2 : 1);
translates into
if (7 > 8)
{
i = 2;
}
else
{
i = 1;
}
See: http://en.wikipedia.org/wiki/%3F:
Your example would return 2 if 7 > 8, or 1 otherwise.
? :
is a ternary operator. This is equivalent to
var x = 0;
if (7 > 8){
x = 2;
} else {
x = 1;
}
It is a terse way of expressing simple conditional statements. It is a great way to conditionally assign values to a variable without the verbose semantics used above.