# Thread: Evaluating prefix/posfix short cut

1. ## Evaluating prefix/posfix short cut

Hey I want to show all of you a supposed "shortcut" evaluating those nasty prefix /posfix expression I found over at the Java boards

Example:

Evaluate for b:

a = 10;
b = a++; //Answer is 10

Now I would tell my students to just rewrite to equvalent:

a = 10;
b = a; // b = 10
a++;

Easy right?

Evaluate for x, given a = 2, b = 3, and c = 2

1. x= a++ + b++; //x = 5

2. x = ++a - --c; // x = 2

3. x = ++a - b++ + ++c; //x = 3

and given a = 10
4. x = a++ + ++a; //undefined in C, but x = 22 in Java

Ugh my student panic with these-- here are the shortcut rules:

1. for any i, subsitute the latest value of i
2. for ++symbol, increment the latest value
3. for -- symbol, decrement the latest value
4. finally do the calculation for all non brackted values
5. be careful when the assigned var is the same as the var which undergone all these ++/-- operations in the statement. In this case the assigned var takes its lastest value. (Which was corrected to say: Since the left hand side var happened to be the var i inteself it takes the value of calculated value.

So using the rules

1. x = 2(3) + 3(4) = 5

2 x = (3)3 - (1)1 = 2

3 x= (3)3 - 3(4) + (3)3 = 3

4. for Java, 10(11) + (12)12 = 22

Now, this shortcut seem to always work for all kinds of ++/-- expressions- we have tried this with a variety of student sand it seems to work.

The written rules seem not to be the clearest.

Thanks to Anna over at Java. We are going to write these rules in notes for our C, c++, C# and Java classes. if you can help us I will give you credit as well for your help.

Thanks Mr. C.

2. I prefer this rule for these types of situtations:
If you don't understand it don't use it

But the rules you listed out aren't very clear like you said. How I would do it:
using number 3 from above
1) sub in the values for the variables:
x = ++(2) - (3)++ + ++(2)
2) do the arithmatic for the ++ and --
x = 3(2) - (3) 4 + 3(2)
3) do the math on the left number in each set and assign to x
4) the unbracketed numbers are the new values of each variable

3. > 3. x = ++a - b++ + ++c; //x = 3
Well the rules for C are simple
1. scan the expression for all prefix and apply
2. evaluate the expression
3. scan the expression for all postfix and apply
If any variable involved in prefix or postfix is touched more than once, then the whole thing is undefined.

4. Thanks, I realize the directions I gave were not clear. We are trying to find better ways to help are students with subjects like this.