Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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){
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading