Search code examples
c#unity-game-engineconditional-operator

Using multiple ternary operators in calculating a int value is not working


I need to calculate a value from an array of integers based on whether they are equal to one on given indexes of the array or not. If they are, the finalValue should be increased by one. So I decided to use multiple ternary operators like this:

int finalValue = (
      tempArray[1] == 1 ? 1 : 0 +
      tempArray[5] == 1 ? 1 : 0 +
      tempArray[8] == 1 ? 1 : 0 +
      tempArray[10] == 1 ? 1 : 0 +
      tempArray[12] == 1 ? 1 : 0 +
      tempArray[15] == 1 ? 1 : 0
);

However, the finalResult is not returning the correct value (It always returns the number one). What am I doing wrong?


Solution

  • Wrap your ternary operators in brackets,

    (tempArray[1] == 1 ? 1 : 0) + (...

    In the current form, this expression is adding on the next expression(s) to the false outcome rather than performing the addition on the result of the expression, and thus you always get 1 or 0 (0 if all indexes in the array are not equal to one, 1 if one or more indexes are equal to 1).

    See the below "pseudo" code for how your ternary operation is evaluated in its current, wrong form.

    if (tempArray[1] == 1) {
        return 1;
    } else {
        return 0 + if (tempArray[5] == 1) { 
            return 1;
        }
        else 
        {
             return 0 + ...
        }
    }
    

    What you're expecting though is the following:

    int finalValue = (
          (tempArray[1] == 1 ? 1 : 0) +
          (tempArray[5] == 1 ? 1 : 0) +
          (tempArray[8] == 1 ? 1 : 0) +
          (tempArray[10] == 1 ? 1 : 0) +
          (tempArray[12] == 1 ? 1 : 0) +
          (tempArray[15] == 1 ? 1 : 0)
    );