Operator priority in c

I am new to programming. Now I am trying to learn the operator priority in C. I am trying to parse the code below.

     #include<stdio.h>
     int main()
     {
        int x, y, z;
        x = y = z= -1;
       z = ++x&&++y&&++z;
       printf("x = %d y = %d z = %d", x, y ,z);
     }

After studying the priority of the operator, I realized that the unary operator has a higher preference. So in the above code

 z = ++0&&++0&&++0;

So, the value of x, y, z is zero, right? But after compilation, I got the answer as x = 0, y = -1 and z = 0.

Can someone help me deal with this issue?

+4
source share
3 answers

When evaluating a logical AND, if the first expression is zero / false means that it will not evaluate the remaining expression. So

 z = ++x&&++y&&++z; // It first increment x, due to pre-increment it becomes zero. 
 // so it wont evaluate the remaining expression in that equation due to Logical AND. it returns 0. (x=0,y=-1,z=-1)
 // but you are assigning return value 0 to z
 z=0;

Try the following code snippets -

   int x, y, z,temp;
   x = y = z= -1;
   temp = ++x&&++y&&++z;
   printf("x = %d y = %d z = %d temp= %d", x, y ,z,temp); // Output 0,-1,-1,0
   x = y = z= -1;
   temp = ++x || ++y&&++z; // But in Logical OR if first expression is true means it wont execute the remaining expression
   printf("x = %d y = %d z = %d temp= %d", x, y ,z,temp); // Output 0,0,-1,0
   x = y = z= -1;
   temp = ++x || ++y || ++z;
   printf("x = %d y = %d z = %d temp= %d", x, y ,z,temp); // Output 0,0,0,0
+2
source

This expression

z = ++x&&++y&&++z;

z = ( ++x && ++y ) && ++z;

C

4 , && ; , . 0, .

, ++x. 0. , ++y .

( ++x && ++y )

0. 0, ++z ( ++x && ++y ) && ++z .

, z , 0.

undefined, , ++z .

, x == 0, y == -1 z == 0 (- ).

+2

Logical AND & and logical OR || evaluated from left to right.

therefore, when evaluating the expression

z = ++x&&++y&&++z;//it evaluates ++x and it becomes 0 so next ++y and ++z are not evaluated so now before assignment x=0,y=-1 and z=-1 and z becomes 0 after assignment

0
source

All Articles