简体   繁体   中英

Can't understand x *= y+1 output

I have a problem understanding the output of the code. Any explanation please...

#include<stdio.h>
void main()
{
     int x=2,y=5;
     x*=y+1;
     printf("%d",x);
}

The output is as 12. But as per my understanding x*=y+1; is x=x*y+1; but as per operator precedence x*y should be evaluated followed by adding 1 so it should be 10+1=11. But it is 12 — can anyone explain please?

It will be evaluated as

x = x * (y + 1);

so

x = 2 * ( 5 + 1 )
x = 12

What's going on here is how the order of operations happens in programming.

Yes, if you were to have this equation x*y+1 it would be (x * y ) + 1 and result in eleven.

But in programming, the equation to the right of the = sign is solved for prior to being modified by the symbol proceeding the = sign. In this equation it is multiplied.

So x *= y + 1 is actually x = x * ( y + 1 ) which would be 12.
^ In this case, the asterisk(*) is multiplying the entire equation on the right hand side by x and then assigning that outcome to x .

It is translated into : x = x*(y+1);

So very obviously it prints out 12.

Your understanding is correct but it's somthing like this:

x*=y+1;  =>  x = x * (y + 1);

Now apply BODMAS

x *= y + 1 is x = x * (y + 1)

Operator + has higher precedence than operator *= .

x*=y; works like x=x*y; and here x*=(y+1) is getting expanded like x = x * (y + 1);

Here from operator procedure in c you can see

Addition/subtraction assignment has lower procedure than simply add operation.

so here

x*=y+1;

+ get executed first.

so

x = x * (6)

so x = 2 * 6

x = 12;

*= and similar ones are a type of C assignment operators , ie these operators are different from * and alike.

Now from C operator precedence , these operators have lowest precedence (higher than , ) hence y + 1 will be evaluated first, then *= will be evaluated and result will be assigned to x .

It evaluates as

x = x * (y + 1);

so

x = 2 * (5 + 1) = 12

Take a look at Operators order , you will see why in this case it is evaluated like that.

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