简体   繁体   中英

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?

Because the order of precedence makes '+' higher than *=, so the 10+2 will occur befor the i *=.

C reference for ordering at http://en.cppreference.com/w/c/language/operator_precedence

In this Line i*= 10+2; In this case the 12 multiply by i It Means i=10*12; So it Will Give 120 In answer

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.

if you wanna answer like 102 the do .

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

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