简体   繁体   English

C运算符的执行顺序

[英]Order of execution of C operators

#include <stdio.h>

int main(void) {

    int i;
    i = 10;
    i*= 10+2;
    printf("%d",i);
    return 0;
}

why is the output of the following code 120 and not 102? 为什么下面的代码120而不是102的输出?

Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=. 因为优先顺序使'+'高于* =,所以10 + 2将在i * =之前出现。

C reference for ordering at http://en.cppreference.com/w/c/language/operator_precedence 有关订购的C参考,网址为http://en.cppreference.com/w/c/language/operator_precedence

In this Line i*= 10+2; 在这一行中,i * = 10 + 2; In this case the 12 multiply by i It Means i=10*12; 在这种情况下12乘以i表示i = 10 * 12; So it Will Give 120 In answer 所以它会给120的答案

To solve this issue Try This. 解决此问题的方法请尝试此。

i*= 10;
i+=2;

your code work like . 您的代码像。

i= i*(10+2)

so it give the answer like 120. 所以给出的答案是120。

if you wanna answer like 102 the do . 如果你想像102那样做。

i=i*10+2 

This 这个

i*= 10 + 2;

is syntactic sugar for 是语法糖

i= i * (10 + 2);

the rest is precedence left to right, add and subst after mult./division 其余的优先级从左到右,在多/除后加和减

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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