简体   繁体   中英

Equal operator in Postfix expression

I'm evaluating postfix expression in c++. Everything is working fine but I've not managed the = equal operator properly.

The Problem causing Infix Expression look like this: A = 2 + B = 5 where A and B are variables. My program convert it into postfix as: 2 5 = B + = A .

In my program I wrote that if current element is an equal operator followed by a variable then move the result in that variable. Which is not proper way to do because my program after solving the above expression gives B = 5 and A = 7 which seems wrong from the expression.

Which technique should I follow to handle the equal operator for my code?

As the comments say, the answer you get is consistent with the rule If current element is an equal operator followed by a variable then move the result in that variable .

However, there is something in the rule that breaks the uniformity of the postfix notation, so I would rather recommend changing that rule to

If the current element is an assignment operator then move the first operand (anything) to the second operand (variable)

For this rule to be applicable you have to validate that the last token (second operand) is a variable.

The rule I propose is consistent with other operations. For instance the postfix notation 3 4 + is converted to 3 + 4 because by the time your scanner reads + it will take the last two operands, 3 and 4 , and sum them: 3 + 4 . In the same way 3 4 + A = would proceed by first saving 3 + 4 as the first operand, then A as the second and finally moving the first operand to the second A = 3 + 4 . Instead, the way you devised the assignment rule is special in that it first reads the operator = and then the second operand A , which will work, but not in the same way as the rest of the operations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM