Conditional and assignment operator in expression

In this example we will be learning how to use conditional and assignment operator in single expression. In previous chapters we have learnt indirect use of if statement in expression

Use of conditional and assignment operator in expression

Consider below example where we have used the conditional and assignment operator in an expression.

#include <stdio.h>
int main(int argc, char *argv[]) {
   int a = 40, b = 30, c;
   c = !a <= !(c = b);
   printf("%d", c);
   return 0;

Output :



Below is the explanation of the complex expression containing conditional and assignment operators –

conditional and assignment operator in expression

Step 1 : Solve the bracket first

While solving an expression, it is thumb rule to solve the bracket first. Lets see how we are solving the brackets –

c = !a <= !(c = b);
c = !a <= !(Assign Value of b to c);
c = !a <= !(30);

so at the end of step 1 our expression will be modified into following expression

c = !a <= !30;

We have replaced the expression (c=b) with 30 in original expression

Step 2 : List our operators with precedence

Now we need to arrange all the operators in the decreasing order of precedence. We are having 2 unary operators, 1 assignment and 1 conditional operator

Re-commanded Article : Operator Precedence and Priority

After listing out all the operators in descending order of priority -

No Operator Name Priority
1 Unary Not Operator Priority 1
2 Unary Not Operator Priority 2
3 Less than or equal to Priority 3
4 Assignment Operator Priority 4

"Not" Operator has higher priority than <= Operator. so we can write it as -

c = !a= !40 = 0

Replace !a by "0" as we calculated it in the above expression statement.

c = 0<=!30

Step 3 : Solve expression recursively

Now again we find there are 3 operators i.e equal to, greater than equal to and Not operator.

"Not" Operator has Higher Priority than any other priority specified in the expression

!30 = 0

so after replacing the expression will be like this -

c = 0 <= 0

Now when we try to solve then we find less than or equal to operator will get higher priority and obviously 0 <= 0 is True condition so it returns 1

c = 1