Must useless expressions be evaluated?
Morris Keesan
keesan at bbncca.ARPA
Fri Oct 14 04:40:16 AEST 1983
I'm working on modifying a C compiler, and in the course of forcing some
type conversion to be generated correctly for assignment expressions I
discovered that the compiler will generate code for almost anything in the
source, whether or not it has any side effects. The particular case in point
is the statement
(char)(i = j);
for which my compiler generates the assignment, followed by code to truncate
(i.e. convert to type "char") the value of the assignment (which is in a
register as a byproduct of the assignment), and then the converted value gets
thrown away as the register is re-used.
This leads to the more general question of whether it is ever legitimate
for a C compiler to ignore operations that have no side effects, or whether I
should always generate what's asked of me. For example:
(i = j) + k + (++l);
Clearly, (i = j) should be performed, as should (++l). But is there any reason
to do either addition? Essentially, the question boils down to whether the
programmer has a right to expect every expression to be evaluated as it falls
into the control flow of the program. I can find no guidance in Kernighan and
Ritchie on this, except in the case of the comma operator and the logical
&&, ||, and ?: operators, which explicitly cause certain operands to be
evaluated. I'd like some opinions on this.
The related question, if people think that some operations are legitimately
ignored when they have no side effects and their value is not used (e.g. when
they appear as expression statements), is which operations? The list of
operations and expressions I've come up with includes casting, all unary
operations except pre and post ++ and --, pointer dereference of all
kinds ( *, ->, [], and . ), all the arithmetic, boolean, shift, and relational
binary operations, and any expression which is simply a variable name or a
constant. For all of these, the C Reference Manual defines what the result or
value of the expression is, but not whether it needs to be evaluated.
Morris Keesan
decvax!bbncca!keesan
{genrad,allegra}!wjh12!bbncca!keesan
keesan at BBN-UNIX.ARPA
More information about the Comp.lang.c
mailing list