Redundant code: Difference between revisions

Content deleted Content added
Rewrote final sentence to make its meaning clearer and remove comma overload.
change source to syntaxhighlight
Line 9:
The following examples are in [[C (computer language)|C]].
 
<sourcesyntaxhighlight lang="C">
int foo(int iX)
{
Line 16:
return iX*2;
}
</syntaxhighlight>
</source>
 
The second <code>iX*2</code> expression is redundant code and can be replaced by a reference to the variable <code>iY</code>. Alternatively, the definition <code>int iY = iX*2</code> can instead be removed.
Line 22:
Consider:
 
<sourcesyntaxhighlight lang="C">
#define min(A,B) ((A)<(B)?(A):(B))
 
Line 30:
return sqrt(min(u1*u1 + v1*v1, u2*u2 + v2*v2));
}
</syntaxhighlight>
</source>
 
As a consequence of using the [[C preprocessor]], the compiler will only see the expanded form:
 
<sourcesyntaxhighlight lang="C">
int shorter_magnitude(int u1, int v1, int u2, int v2)
{
Line 44:
return sqrt(temp);
}
</syntaxhighlight>
</source>
 
Because the use of min/max macros is very common, modern compilers are programmed to recognize and eliminate redundancy caused by their use.
 
There is no redundancy, however, in the following code:
<sourcesyntaxhighlight lang="C">
#define max(A,B) ((A)>(B)?(A):(B))
 
Line 56:
return max(cutoff, rand()%range);
}
</syntaxhighlight>
</source>
 
If the initial call to rand(), modulo range, is greater 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 thus may not produce the intended behavior for this function.