What happens in C prog while executing the following expression: x = 4 + 2 % - 8 ; The answer it outputs is 6,but I didn't get how this snippet is actually executed?
4 Answers
In this case - is the unary negation operator (not subtraction) and it binds tightly to the 8 literal as it has a very high precedence. Note that formally there are no such things as negative literals in c.
So, the modulus term is evaluated as 2 % (-8). The modulus operator has the same precedence as multiplication and division.
Comments
The language does not define how it is executed since the expression is not sufficiently sequenced to force a specific execution schedule (order of evaluation).
All we can potentially tell you is what it evaluates to. Since you did not provide us with the exact type of x, it is not really possible to tell what the whole expression evaluates to. For this reason I will restrict consideration to the 4 + 2 % -8 subexpression.
This subexpression is grouped as
4 + (2 % (-8)) Since 2 / (-8) is 0 in modern C, 2 % (-8) is 2. So the above subexpression evaluates to 6.
P.S. Note that in C89/90 2 / (-8) could legally evaluate to -1 with 2 % (-8) evaluating to -6. The whole thing would evaluate to -2.
Comments
The expression give precedence to % first so it evaluates (2 % -8) = 2 and then add 4 to it. So ans is 4 + 2 = 6.
%-8would be invalid if-was the subtraction operator.x = 4 + 2 % - 8expression conceptually includes conversion of the RHS to the type ofx. You did not provide us with the type ofx.