简体   繁体   中英

Operator precedence in C explanation

I have the following code:

#include<stdio.h>
void main(){
int x;
x=1%9*4/5+8*3/9%2-9;
printf("%d \n", x);
}

The output of the program is -9 . When I tried to breakdown the code according to operator precedence (* / %,Multiplication/division/modulus,left-to-right) answer turns out to be -8 .

Below is the breakdown of the code:

x=1%9*4/5+8*3/9%2-9;
x=1%36/5+24/9%2-9;
x=1%7+2%2-9;
x=1+0-9;
x=-8;

Can someone explain how the output is -9 .

It appears that you consider modulo to have lower precedence than multiplication and division, when in fact it does not. Instead of

x = (1 % ((9 * 4) / 5)) + (((8 * 3) / 9) % 2) - 9;

the expression you have really represents

x = (((1 % 9) * 4) / 5) + (((8 * 3) / 9) % 2) - 9;

The modulo in the first summand is applied before the multiplication and division.

x = 1%9*4/5+8*3/9%2-9
== 1*4/5+24/9%2-9
== 4/5+2%2-9
== 0+0-9
== -9

All these operators *, /, % belong to the category of multiplicative operators. Their grouping is more clearly described in the C++ Standard (the same is valid for the C Standard) 5.6 Multiplicative operators:

1 The multiplicative operators *, /, and % group left-to-right .

Thus this expression statement

x=1%9*4/5+8*3/9%2-9;

is equivalent to the following statement

x = (( ( 1 % 9 ) * 4 ) / 5 ) + ( ( ( 8 * 3 ) / 9 ) % 2 ) - 9;

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