-3

What does this mean?

I have problem understanding this because I'm not using this kind of format.

Can anyone translate this condition?

(D == 4 ? (i % 2 == 0 ? 10 : 14) : 10);
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
GeekUp
  • 51
  • 1
  • 8

3 Answers3

2

This is two ternary operators. The ternary operator compresses an if-else statement into one line. (expression ? fireOnTrue() : fireOnFalse()) For example

if(D == 4) {
    explode();
} else {
    explodeTwice();
}

could be written as:

D == 4 ? explode() : explodeTwice()

Therefore, if we take (D == 4 ? (i % 2 == 0 ? 10 : 14) : 10); and break it down we get:

if(D == 4) {
    (i % 2 == 0 ? 10 : 14);
} else
    10;
}

breaking that down one more step gives us:

if(D == 4) {
    if(i % 2 == 0) {
        10;
    } else {
        14;
    }
} else
    10;
}
Dbz
  • 2,721
  • 4
  • 35
  • 53
1

Let's go through that monster piece by piece.

(D == 4 ? (i % 2 == 0 ? 10 : 14) : 10)

This line uses the ternary operator x ? y : z, which returns

  • y if x == true
  • z if x == false

(D == 4 ? (i % 2 == 0 ? 10 : 14) : 10) first checks whether D is equal to 4:

  • if D is equal to 4 it returns (i % 2 == 0 ? 10 : 14)
  • if D is not equal to 4 it returns 10.

If D happens to be equal to 4 then expression (i % 2 == 0 ? 10 : 14) will be parsed:

(i % 2 == 0 ? 10 : 14) first checks whether i % 2 == 0 is true or false. % is the remainder aka modulo operator which returns the remainder of the division a/b for a % b.

Comparing that result to 0 is the same as saying "divides evenly", i.e. no remainder.

The remainder for dividing by 2 can be either 0 or 1, thus:

  • 0 if i is an even number
  • 1 if i is an odd number

In other words, (i % 2 == 0 ? 10 : 14) will return 10 if i is even, or 14 if i is odd.


In conclusion, (D == 4 ? (i % 2 == 0 ? 10 : 14) : 10) has can evaluate to either 10 or 14 depending on D and i, like this:

  • if D == 4 and i is even, it evaluates to 10
  • if D == 4 and i is odd, it evaluates to 14
  • if D != 4, it evaluates to 10

Thus, the expression could be simplified as a method to this:

int return10or14(int D, int i) {
    if (D != 4 || i % 2 == 0)
        return 10;
    else
        return 14;
}
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
0

The expression a ? b:c simply means if(a) then b , else c. Thus assuming your expression evaluates to retval, it can be written as:

if(D == 4)
{
    if(i%2 == 0) 
      retval = 10;
    else 
      retval = 14;
}
else  retval = 10;
eral
  • 123
  • 1
  • 16