In computer programming, '''redundant code''' is source code or compiled code that is unnecessary. Code that can be removed without affecting its desired behavior is redundant.
==Categories== Notable categories of redundant code include:
; Recomputing: Calculating again a value that has previously been calculated<ref>[http://doi.acm.org/10.1145/349214.349233 Debray, S. K., Evans, W., Muth, R., and De Sutter, B. 2000. Compiler techniques for code compaction. ACM Trans. Program. Lang. Syst. 22, 2 (Mar. 2000), 378–415.]</ref> and is still available.
; Dead code: Code that is executed but has no external effect (i.e., does not change the output produced by a program).
; Unreachable code: Code that is never executed (also called dead code).
; NOP padding: A NOP instruction might be considered redundant if it is for padding. But if the NOP is required for proper functionality, then it is not redundant.
; Unused identifier: Something declared, but never referenced, is a redundant declaration.
==Examples== In the following C code, the second <code>x * 2</code> expression is redundant code. Line 2 can be removed, or alternatively, line 3 can be changed to {{code| return y;}}.
<syntaxhighlight lang="C" line> int foo(int x) { int y = x * 2; return x * 2; } </syntaxhighlight>
A more subtle example involves the C preprocessor that inserts code before compilation. Consider:
<syntaxhighlight lang="C"> #define min(A,B) ((A)<(B)?(A):(B)) int shorter_magnitude(int a, int b, int c, int d) { return sqrt(min(a*a + b*b, c*c + d*d)); } </syntaxhighlight>
After preprocessing, the code expands to code that evaluates both {{code|a*a + b*b}} and {{code|c*c + d*d}} twice. To eliminate the duplicate code, the macro {{code|min}} could be converted to a function.
<syntaxhighlight lang="C"> int shorter_magnitude(int a, int b, int c, int d) { return sqrt(((a*a + b*b)<(c*c + d*d)?(a*a + b*b):(c*c + d*d))); } </syntaxhighlight>
==See also== * {{Annotated link |Code bloat}} * {{Annotated link |Code reuse}} * {{Annotated link |Common subexpression elimination}} * {{Annotated link |Don't repeat yourself}} * {{Annotated link |Duplicate code}} * {{Annotated link |Redundancy (information theory)}} * {{Annotated link |Code refactoring}} * {{Annotated link |Code smell}}
==References== {{Reflist}}
Category:Compiler optimizations Category:Software anomalies Category:Source code