Please correct me if wrong, to solve this statement, the num1++(0) would be executed first due to highest precedence and then ++num1(2) would be executed and then at last && will be preformed because it has the lowest precedence.
Precedence only controls which operators are grouped with which operands - it does not affect the order in which expressions are evaluated.
The &&
, ||
, ?:
, and comma operator all force left-to-right evaluation - the left operand is fully evaluated (and any side effects applied) before the right operand. &&
and ||
both short circuit - for &&
, the right operand will be evaluated only if the left operand is non-zero.
The unary (prefix) ++
operator yields the current value of the operand plus 1, so the result of ++num1
is 1
. As a side effect the value in num1
is incremented. Since this result is non-zero, num1++
is also evaluated. The postfix ++
operator yields the current value of the operand, so the result of num1++
is 1
. As a side effect the value in num1
is incremented.
The result of an &&
expression is 1
if both operands are non-zero, 0
otherwise.
It's roughly equivalent to writing
tmp = num1 + 1;
num1 = num1 + 1;
res = 0;
if ( tmp != 0 )
{
if ( num1 != 0 )
{
res = 1;
}
}
num1 = num1 + 1;
So the result of ++num1 && num1++
is 1
, and the value stored in num1
at the end of it is 2
.
In some of the tutorials I find that postfix ++ and prefix ++ have the same precedence,
That is very wrong and you should stop using those tutorials immediately. Postfix operators have higher precedence than unary operators - *a++
is parsed as *(a++)
, ++a[i]
is parsed as ++(a[i])
, etc. An expression like ++i++
would be parsed as ++(i++)
, but you can't write such an expression in C - the result of i++
isn't an lvalue and cannot be the operand of a unary ++
like that.