简体   繁体   中英

How does operator precedence grouping work in C for *, /, and %?

Referring to the O'Reilly pocket reference for C, I'm a little confused by the description for grouping of the * , / , and % operators. The book says that grouping occurs left to right -- now I think I'm getting grouping confused with evaluation order. Given the following equation, and the rules established from the book, I would have thought that...

int x = 4 / 3 * -3

... evaluates to 0 , because...

1: 4 / 3 * -3
2: 4 / -9
3: 0

... however, it actually evaluates to -3 , and it seems to use this method...

1: 4 / 3 * -3
2: 1 * -3
3: -3

Why is that?

It makes sense to me:

int x = 4 / 3 * -3;

Grouping left to right, we get:

int x = (4 / 3) * -3
int x = ((4 / 3) * -3);

Also see the precedence table . They are at the same precedence, so they bind left to right.

You need to know both the precedence and the associativity of operators.

Multiplication (*) has higher precedence than addition (+), which is why 2+3*4 is interpreted as 2+(3*4), both in C and normal math. But in an expression like 2*3/4, or 2*3*4, the operators all have the same precedence, and you need to look at the associativity. For most operators, it is left to right, which means that you start grouping from the left: 2*3/4 becomes (2*3)/4, 2*3*4*5 becomes ((2*3)*4)*5, and so on.

An exception is assignment, which is an operator in C. Assignment is right associative, so a=b=3 should be read as a=(b=3).

Any good C book or tutorial should have a table of all the operators (such as this one ), with both precedence and associativity.

Visit the following URL. It is very useful all the topics in C. So you can use the operator precedence also.

 http://www.goldfish.org/books/The%20C%20Programming%20Language%20-%20K&R/chapter2.html#s2.12

Here , it is left associative for system recognisation . So , it will execute second example only for evaluating the expression.

IMHO, it is good to know about these operator precedences, but it is better to use parentheses whenever there is doubt :-). As the masters say, the code is more for human readers than for the machine; if the author is not sure, nor will be the readers.

这些 链接应该可以帮助您。

乘法和除法保持关联,因此发生的是第二顺序-运算分组为(4/3),然后将结果乘以-3。

For math, C works just like you learned in high scool. Remember BODMAS (Brackets of Division, multiplication, addition and subtraction). This means it looks for a calculation from the left to the right. In this case it sees 4/3 and calculates the answer, then multiplies the answer with -3. You can use brackets to fix that ( 4/(3*-3) ). Have a look at this page for a summary of how C orders operators and performs the calculations.

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