vipil
vipil

Reputation: 85

precedence of operator in c

I am new to programming. Right now I am trying to learn precedence of operator in C. I try to analyse the code givenbelow.

     #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 learning precedence of operator, I understood unary operator has higher preference. So in the above code

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

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

Can any one help me to figure out this issue??

Upvotes: 4

Views: 869

Answers (3)

shashank
shashank

Reputation: 410

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

so in the evaluation of 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

Upvotes: 0

Vlad from Moscow
Vlad from Moscow

Reputation: 310910

This expression

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

is equivalent to the following expression

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

According to the C Standard

4 Unlike the bitwise binary & operator, the && operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

So at first ++x is evaluated. It will be equal to 0. So ++y will not be evaluated. Expression

( ++x && ++y )

will be equal to 0. As it is equal to 0 then sub-expression ++z in expression ( ++x && ++y ) && ++z will not be evaluated.

Thus z will be assigned the value of the full expression that is equal to 0.

There is no any undefined behaviour at least because expression ++z will not be evaluated.

So you will get x == 0, y == -1, and z == 0 (due to the assignment operator).

Upvotes: 2

Sathish
Sathish

Reputation: 3870

In evaluating logical AND, If the first expression is zero/false means it wont 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

Upvotes: 2

Related Questions