Normally, I usually see i++; or ++i;. However, this is my first time to see something like this:
val = val == 0 ? 0 : 1;
What does it mean?
Normally, I usually see i++; or ++i;. However, this is my first time to see something like this:
val = val == 0 ? 0 : 1;
What does it mean?
The code val = val==0?0:1; is a shorter representation of this code:
if (val==0)
{
val = 0;
}
else
{
val = 1;
}
The syntax of a?b:c is:
<condition> ? <result if true> : <result if false>
It is using the ternary conditional operator, which looks like
condition ? [value if true] : [value if false].
In this case, it is saying that if val == 0, then set val to 0; otherwise, set val to 1.
Hope this helps!
This is the so-called ternary operator, which can be viewed as an "immediate if" expression, that is to say:
val = val == 0 ? 0 : 1;
amounts to:
if (val == 0) {
val = 0;
} else {
val = 1;
}