Sakib Hasan - 2 months ago 7x

C Question

1st part:

`i=j=k=1;`

m = ++i && ++j || ++k;

printf("%d, %d, %d, %d\n", i, j, k, m);

output: 2, 2, 1, 1

1st part easily understood ,Here

`++i && ++j`

2nd part:

`i=j=k=1;`

m = ++i || ++j && ++k;

printf("%d, %d, %d, %d\n", i, j, k, m);

output: 2, 1, 1, 1

2nd part confusing to understand ,Here

`++i || ++j`

`++i`

`i`

`j`

`k=2`

Dear altruist, please explain me what happen in 2nd part.

Answer

&& has higher priority than || in C/C++, rendering your code as:

```
m = ++i || (++j && ++k);
```

As `++i`

is already true, the second part is not executed.

See http://de.cppreference.com/w/cpp/language/operator_precedence for operator precedences and http://en.wikipedia.org/wiki/Short-circuit_evaluation for short-circuit_evaluation.

Source (Stackoverflow)

Comments