Would anyone be kind enough to explain what infix, postfix and prefix notation is in regards to the C programming language?
Thanks, ~Daniel
Would anyone be kind enough to explain what infix, postfix and prefix notation is in regards to the C programming language?
Thanks, ~Daniel
Here is a good discussion of the three terms, and how they apply.
The C language uses infix notation nearly everywhere. For example, you'd do:
x = 4 + 2;
However, there are a couple of operations that use prefix notation, such as negation:
x = -y; // "-" is using prefix notation
Postfix is used for operations such as incrementation (++):
x = y++;
Some examples for each:
Infix:
a + b
a * b
Postfix:
a++
f()
a[i]
Prefix (also called "unary" in C and C++):
++a
&a
-a
The C language definition isn't quite so clear-cut about infix vs. prefix vs. postfix; the terms "prefix" and "infix" don't even appear in the language definition as such. Instead, you have binary operator expressions (sort-of infix) and unary expressions (sort-of prefix). Also, the groupings of expressions into postfix, unary, and binary categories has more to do with which expressions should have higher precedence than others, rather than where the operators appear in the expression.
For example, the &&
and ||
operators look like they should be grouped with the binary operator expressions, but they're not; they occupy their own space in the language grammar and they have their own unique semantics. The component selection operators .
and ->
are grouped with the postfix operators, even though they appear between two expressions, because component selection should always have higher precedence than, say, address indirection (i.e., &a.b
should always be parsed as &(a.b)
, not (&a).b
) and also because the right-hand operand must always be an identifer.
Postfix expressions include the following:
a[i]
)a->b
, d.c
)foo(a,b)
)a++
, b--
)(int []) {1, 2, 3}
)All postfix expressions have higher precedence than unary or binary expressions.
Unary expressions include the following:
(int) foo
)sizeof foo
, sizeof (int)
)-5
)+1
)!expr
)~byte
)&foo
)*ptr
)++foo
, --bar
)Unary expressions have higher precedence than binary expressions, but lower precedence than postfix expressions.
Binary expressions include the following:
a * b
, c / d
)a + b
, c - d
)a << b
, val >> 2
)a < b
, c >= d
)a == b
, c != d
)a & b
, c | d
, e ^ f
)Binary expressions have lower precedence than both postfix and unary expressions.
In addition to these groupings, you also have the logical operator expressions (&&
and ||
), conditional expressions (a ? b : c
), which have a lower precedence than binary expressions, assignment expressions (a = b
, c += d
), sequential expressions (a, b, c
), and constant expressions (int a[42]
, case 5:
), which are different from the literals classed with postfix expressions.