Operator precedence with value change within expression
Learning operator precedence case when value changes while evaluating the expression.
Learning Objectives
- Learning to deduce the precedence when a variable value changes while in the expression building itself, like for pre-increment, decrement cases.
Source Code
|
Run Output
Code Understanding
int x=2,y=5;
int n=x – –y + y/x * (x*y++);
Let us build this formula one by one following the precedence rules and replacing the variables with given values of x and y.
2 – 4 + 4/2 * (2*4) //we write it from left to right. first y is decremented to 4 which value is subsequently used for other places of y
2 -4 + 4/2 * 8
2-4+ 2 * 8
2-4+16 //we reduce it to a level of addition and subtractions by first solving bracket and then division and then multiplication
2-4+16 = 14 //This is final deduction
int n1=–x – (y + y/x);
Since previous statement had last y as y++ so in this statement incremented value of y would be used. this would be 5 as earlier y was decremented from 5 to 4 and here it would be again incremented to 5. Now making further deductions with precedence rules.
1 – (5 + 5/1) //solving left to right x will decremented first and subsequent x will be same decremented value which is 1.
1 – (5 + 5) //Here we try to work the bracket first followed by division
1 – 10 = – 9 // We come to final deduction level here.
Notes
- Some older compilers follow different inline deduction rules. For example they may not be able to update prefix operator changes while building the formula. So the exact answers may be different. For example the answer for above problem in dos based turboc++ compilers would be different. This anomaly can only be removed by using latest c++ standards from c++ 2011 onwards.
Suggested Filename(s): op-prec-valchange.cpp
sunmitra| Created: 19-Dec-2017 | Updated: 31-Aug-2018|