cif-statementoperator-precedencecompound-assignment

i*=j ==x and i=i*j ==x behaving differently in C


I have these two code snippets that are acting differently:

int i=2,j=3;
if (j*=i == 2){
    printf("yes, i= %d, j= %d",i,j);
} else {
    printf("no, i= %d, j= %d",i,j);
}
int i=2,j=3;
if (j=j*i == 2){
    printf("yes, i= %d, j= %d",i,j);
} else {
    printf("no, i= %d, j= %d",i,j);
}

I assume that the right operand is being compared with 2 first, ie j*=(i==2) and j=(j*i==2) respectively, where the first returns 1 and multiplies it with j resulting in the output yes, i= 2, j= 3, and the second returns 0 and multiplies it resulting in no, i= 2, j= 0.

My question is why is *=i different from =j*i? Does the compiler just take the right operand immediately because comparison has a higher precedence?


Solution

  • As you've figured out, the multiplication operator * has higher precedence than the equality operator ==, which in turn has higher precedence than the assignment operators = and *=.

    So this:

    if (j*=i == 2){
    

    Is the same as this:

    if (j*=(i == 2)){
    

    And this:

    if (j=j*i == 2){
    

    Is the same as this:

    if (j=((j*i) == 2)){
    

    You would get the same result using = and *= if you used parenthesis like this:

    if ((j*=i) == 2){
    ...
    if ((j=j*i) == 2){