Sakib Hasan Sakib Hasan - 4 months ago 8
C Question

Why isn't “k” incremented in the statement “m = ++i || ++j && ++k”?

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
execute first, which is true (and increment value of i and j) so there is no need to check next part of OR operation(no need increment value of k) .

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
execute first, in which
++i
is true (and increment value of
i
, since OR opreation so no need to increment value of
j
). Next execute AND operation here should be increment value of
k=2
(but still value of k print 1).

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.

Comments