0

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?

2
  • 1
    %-8 would be invalid if - was the subtraction operator. Commented Sep 25, 2016 at 15:58
  • Formally speaking, the evaluation of the whole x = 4 + 2 % - 8 expression conceptually includes conversion of the RHS to the type of x. You did not provide us with the type of x. Commented Sep 25, 2016 at 16:22

4 Answers 4

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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

1

The expression give precedence to % first so it evaluates (2 % -8) = 2 and then add 4 to it. So ans is 4 + 2 = 6.

Here is quick reference for you.

Comments

0

The unary - operator has the highest precedence here.

The % operator has precedence equal to that of the / and * operators, which is therefore higher than that of the + operator.

Bottom line, 4 + 2 % -8 is equivalent to 4 + (2% (-8)).

Comments