Home > Software engineering >  Using multiple ternary operators in calculating a int value is not working
Using multiple ternary operators in calculating a int value is not working

Time:02-04

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?

CodePudding user response:

The issue is with the way the ternary operators are used, as the ternary operator ? : has lower precedence than the addition operator . This means that the expression inside the parentheses is evaluated as (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. The first ternary operator is evaluated as 1 (since tempArray[1] is equal to 1), and then the expression is evaluated as 1 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, where tempArray[5] == 1 is true, so it is evaluated as 1 1 tempArray[8] == 1 ? 1 : 0 tempArray[10] == 1 ? 1 : 0 tempArray[12] == 1 ? 1 : 0 tempArray[15] == 1 ? 1 : 0, and so on.

To fix the issue, you can use parentheses to ensure that the ternary operator is evaluated before the addition operator:

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)
);

CodePudding user response:

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)
);
  • Related