What is the Difference Between Prefix and Postfix?

🆚 Go to Comparative Table 🆚

The main difference between prefix and postfix lies in the position of the operators in relation to their operands. In prefix notation, operators precede the operands, while in postfix notation, operators follow the operands. Here are more details about each notation:

Prefix Notation:

  • Operators are placed before their operands.
  • Example: Infix notation: A + B; Prefix notation: + AB.
  • Commonly used in programming languages like LISP.
  • Can be evaluated faster than infix notation.
  • Easier to parse for machines.
  • No issue of operator precedence or left-right associativity.

Postfix Notation:

  • Operators are placed after their operands.
  • Example: Infix notation: A + B; Postfix notation: AB +.
  • Used in intermediate code generation in compiler design.
  • Easier to parse compared to infix notation.
  • Fewer overheads with parentheses, taking less time for parsing.
  • Less ambiguous, making it faster to evaluate compared to other notations.

In the context of increment and decrement operators, the difference between prefix and postfix versions lies in the order of operations. In prefix increment (++i), the value of i is incremented before the expression is evaluated, while in postfix increment (i++), the expression is evaluated before the value of i is incremented. The same applies to the decrement operator (--).

Comparative Table: Prefix vs Postfix

The main difference between prefix and postfix is the position of the operator in relation to the operands in an expression. Here is a table summarizing the differences:

Feature Prefix Postfix
Operator Placement Operator precedes the operands Operator follows the operands
Infix Expression A + B * C A B C * +
Prefix Expression + A * B C A B C * +
Postfix Expression A B C * + A B C * +

In a prefix expression, the operator precedes the operands, and in a postfix expression, the operator follows the operands. The order of operations remains the same in both cases, but the position of the operator changes. For example, consider the infix expression A + B * C. In prefix notation, it becomes + A * B C, and in postfix notation, it becomes A B C * +. The precedence of operators is respected in both cases.