-3

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?

Ivar
  • 6,138
  • 12
  • 49
  • 61
Mr.Kim
  • 186
  • 1
  • 10
  • 1
    FYI you should never write code like this. – bhspencer Apr 15 '18 at 17:35
  • @bhspencer It depends. If the variables and methods are properly named and the line is short and understandable, it is a good choice. – Edu Apr 15 '18 at 17:41
  • 1
    In addition to the already correct answers, I find it as being overkill to do `val = val == 0 ? 0 : 1;` , instead simply do `if(val != 0) val = 1;` – Ousmane D. Apr 15 '18 at 17:46

4 Answers4

3

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>
Edu
  • 2,354
  • 5
  • 32
  • 36
2

It means if val == 0 then set val to 0 else set val to 1

Sam
  • 2,350
  • 1
  • 11
  • 22
DCR
  • 14,737
  • 12
  • 52
  • 115
2

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!

Sam
  • 2,350
  • 1
  • 11
  • 22
2

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;
} 
ErikMD
  • 13,377
  • 3
  • 35
  • 71