简体   繁体   中英

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?

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.

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 .

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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM