Infix vs Postfix
Had this question in the interview yesterday. Which is better to use? Infix(with parenthesis) or Postfix? State with reason..
I only could tell them that:
- it is easier for the compilers to process postfix expression for arithmetic evaluations and operator precedence.
- More memory is used for storing and processing the paren开发者_JS百科thesis.
Please throw some light on whether I am right on this?
Postfix doesn't require any operator-driven order of operations; it's always explicit. So for a stack-based compiler, it's very easy to implement, and for humans, it's easy to understand the order of operations.
On the other hand, infix doesn't require you to read all the verbs at the end :-P. Humans work on infix or even prefix; "add A to B" makes more sense than "A and B: add them".
But, this question is fundamentally subjective. Postfix will always be better for the computer system, but infix has its merits.
Memory is not usually an issue here. Compilers spend tons of memory on other things. Postfix usually entails an operand stack, which involves a certain amount of memory (still small) at runtime.
Postfix is useful for low-level interpretable code, such as Java, Forth, Postscript. These all have hardware or super-lightweight software implementations.
Infix is better for readability.
Of course, there's no way to know how the issue affects your field without knowing what kind of job it is.
The similarity between Infix, Postfix and Prefix:
- Order of operands is same in the three notations(but the order of operators changes, hence the names also)
Differences between Infix, Postfix and Prefix:
- Infix is more human-readable. That's why it is very commonly used in mathematics books.
- Infix has to add more information to remove ambiguity. So, for example, we use parenthesis to give preference to lower precedence operator, but in postfix we have order of operators. (as mentioned by @EJP here
- Postfix and Prefix are more machine-readable. So for instance, in postfix, every time you encounter a number, put it on a stack, every time you encounter an operator, pop the last two elements from the stack, apply the operation and push the result back.
Thanks
精彩评论