Breaking Benjamin - 1 month ago 17
C Question

# Ternary operator precedence in c

In the following code output is 1 but it should be 2 . how ?

``````#include<stdio.h>

int main()
{
int count=0,i;
int num[4]={1,2,3,4};

for(i=0;i<4;++i)
count = count+(num[i]%2==1)?1:0;

printf("%d",count);
return 0;
}
``````

Operator precedence. Change the line to:

``````    count = count + ((num[i] % 2 == 1) ? 1 : 0);
``````

Or, even better:

``````    count += num[i] % 2;
``````

To explain: `+` has a higher precedence than `?:`. So your line as-is is actually being interpreted as:

``````    count = (count + (num[i] % 2 == 1)) ? 1 : 0;
``````

So on each iteration of the loop, count is being set to either `1` or `0`, as follows:

``````  i   |  count  |  (num[i] % 2 == 1)  | count + (num...)  |  new count
------+---------+---------------------+-------------------+-------------
0   |    0    |      1 (true)       |      1            |    1
1   |    1    |      0 (false)      |      1            |    1
2   |    1    |      1 (true)       |      2            |    1
3   |    1    |      0 (false)      |      1            |    1
``````
Source (Stackoverflow)