user6360223
user6360223

Reputation:

Operator precedence in C

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?

Upvotes: 0

Views: 130

Answers (4)

AnT stands with Russia
AnT stands with Russia

Reputation: 320777

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.

Upvotes: 2

Bathsheba
Bathsheba

Reputation: 234875

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.

Upvotes: 2

barak manos
barak manos

Reputation: 30146

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)).

Upvotes: 0

RohitS
RohitS

Reputation: 1046

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.

Upvotes: 1

Related Questions