The following code is supposed to implement constant-folding for equations as given by the specification:
bool equation::constant_fold(void) {
return lhs->constant_fold() || rhs->constant_fold();
}
Does the code implement the specification? Explain.
The code does not implement the specification. The problem arises from the
logical or operator ||. Logical or is a short-circuiting operator, that
is, when evaluating a || b, a is evaluated first and, if true, b is
not evaluated (because the or of a true value with anything is true).
This short-circuit behavior causes problems in equation::constant_fold()
when lhs->constant_fold() returns true, because then
rhs->constant_fold() is never called, which is contrary to the
specification that both sides of the equation be folded.
Unfortunately, the question as it appeared on the test had a typo in it: I
forgot the rhs-> before the second fold_constant() call. Correct
answers based on the typo also received full credit.
This question is based, of course, on an error I made while coding up the fourth assignment.
p and q have type T*, explain what the value p -
q represents. Are there are any other conditions that must hold for your
answer to be correct? If so, what are they?
The expression p - q gives the number of elements between p and
q, including the element *p but not the element *q (or vise
versa if you prefer).
However, for p - q to have a meaningful value, both p and q must
point to elements in the same array.
Many people wrote only that that p - q is the difference between p
and q without giving the units or mentioning that it's a non-inclusive
difference.
double student_info::grade() const {
return ::grade();
}
explain the use of :: in the return statement.
The second scope operator refers to the grade() procedure in the program's
global scope. It is used to jump around the local definition of
student_info::grade(); without the ::, the inner call to grade()
would refer to the local definition and infinite recursion would result.
Almost nobody noted that ::grade() is an access to global scope; many
people claimed the std name space was somehow involved, which it isn't.
char * cp = new char[30];
and the statement
char * cp = new char(30);
The first statement defines an array of 30 characters, each element of which is undefined. The second statement defines an array of 1 character, which is initialized to the character equivalent to the integer value 30 (which is a non-printing ASCII character).
This was straight out of the book (page 183, or §10.4/183 I suppose). This
question is amusing because it came from a 305 student. He came into my office
and asked me for help in figuring out why his program was crashing. It took me
about five minutes before I noticed that he had typed new char(30) rather
than new char[30].
This page last modified on 6 December 2001.