Examples
int foo(int iX) { int iY = iX*2; return iX*2; }The second iX*2 expression is redundant code and can be replaced by a reference to the variable iY. Alternatively, the definition int iY = iX*2 can instead be removed.
Consider:
#define min(A,B) ((A)<(B)?(A):(B)) int shorter_magnitude(int u1, int v1, int u2, int v2) { /* Returns the shorter magnitude of (u1,v1) and (u2,v2) */ return sqrt(min(u1*u1 + v1*v1, u2*u2 + v2*v2)); }As a consequence of using the C preprocessor, the compiler will only witness the expanded form:
int shorter_magnitude(int u1, int v1, int u2, int v2) { int temp; if (u1*u1 + v1*v1 < u2*u2 + v2*v2) temp = u1*u1 + v1*v1; /* Redundant */ else temp = u2*u2 + v2*v2; /* Redundant */ return sqrt(temp); }Because the use of min/max macros is very common, modern compilers are trained to recognize and eliminate redundancy caused by their use.
There is no redundancy, however, in the following code:
#define max(A,B) ((A)>(B)?(A):(B)) int random(int cutoff, int range) { /* Returns (cutoff, cutoff, cutoff, ..., cutoff+1, cutoff+2, ... range) */ return max(cutoff, rand%range); }The reason is that its implementation is incorrect. If the initial call to rand, modulo range, is less than or equal to cutoff, rand will be called a second time for a second computation of rand%range, which may result in a value that is actually lower than the cutoff. The max macro will thus not work for this function.
Read more about this topic: Redundant Code
Famous quotes containing the word examples:
“There are many examples of women that have excelled in learning, and even in war, but this is no reason we should bring em all up to Latin and Greek or else military discipline, instead of needle-work and housewifry.”
—Bernard Mandeville (16701733)
“No rules exist, and examples are simply life-savers answering the appeals of rules making vain attempts to exist.”
—André Breton (18961966)
“In the examples that I here bring in of what I have [read], heard, done or said, I have refrained from daring to alter even the smallest and most indifferent circumstances. My conscience falsifies not an iota; for my knowledge I cannot answer.”
—Michel de Montaigne (15331592)