'C' Operators precedence

Richard B. Johnson (root@chaos.analogic.com)
Tue, 19 May 1998 21:40:51 -0400 (EDT)

There were two others on this thread, but I was interrupted by a
'work break' so I hit the 'D' key.

In the case of:

a = b + c + f(d);

... f(d) must be evaluated first because of the precedence
of the () operator.

It is important to understand what f(d) really means. It
means to evaluate 'd' using an object called 'f'. F is not
necessarily a function. It could be a macro.

The closing of a parenthesis means "evaluate the objects
between the opening and closing parenthesis". In some texts,
"()" is called the evaluation operator. Each time an
evaluation operation is complete, a sequence-point is
established. This is the only reason why objects are
evaluated before a function is called. The "()" operator
forces this.

This is also the reason why calling a function through a
pointer must use 'extra' parenthesis:

r = (*f)(a);

... since

(*f) closes the parenthesis

... and

(a) closes the parenthesis

... evaluation occurs left-to-right as:

de-reference pointer 'f', then evaluate 'a' using the
object addressed by it.

If we didn't have the extra set of parenthesis as:

c = *f(a);

... we tell the compiler to evaluate 'a' using object 'f'
which has not been de-referenced yet, which will not work.
FYI, some compilers allow c = f(a), where 'f' is a pointer.
This is bogus and helps prevent 'C' writers from learning
what they are really doing.

When seeing ONLY:

a = b + f(c);

... the compiler must evaluate 'c', using object 'f', first
because '()' has the highest precedence of any 'C' operator.

When seeing:

a = f(b) + g(c);

... the compiler is still not free to evaluate 'b' and 'c'
in any order because of association, also called
associativity, which requires operators of identical
precedence to be evaluated left-to-right. This is why the
functions (or macros) will be evaluated left-to-right.

When seeing:

a = b() + c();

.... the compiler is told to evaluate nothing (void) using
object 'b', then evaluate nothing using object 'c'.

When seeing:

a = b + c + d;

... the compiler may still not legally evaluate the objects
in any order because of associativity, but many/most do.
Optimization is not yet part of the 'C' standard. When
attempting to optimize code, certain standards are broken as
long as the code is likely to work.

Everything makes sense once one understands the '()' operator.

Dick Johnson
Penguin : Linux version 2.1.101 on an i586 machine (66.15 BogoMips).
Warning : It's hard to remain at the trailing edge of technology.

To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.rutgers.edu