June 1, 2010

[Tom] Duff's Device

Duff's Device is mentioned in the JLS section about switch statements. The nitty-gritty is explained at this StackOverflow answer.

Sample code:

package pkg;

public class Foo
{
public static void main(String args[])
{
int numTimesToCallMethod = 20;
int numTimesToRunWhile = (numTimesToCallMethod + 7) / 8;

switch (numTimesToCallMethod%8)
{
case 0:
do {
IllHaveADuffYouHaveOneToo(); // Great C hack, Tom,
case 7: IllHaveADuffYouHaveOneToo(); // but it's not valid here.
case 6: IllHaveADuffYouHaveOneToo();
case 5: IllHaveADuffYouHaveOneToo();
case 4: IllHaveADuffYouHaveOneToo();
case 3: IllHaveADuffYouHaveOneToo();
case 2: IllHaveADuffYouHaveOneToo();
case 1: IllHaveADuffYouHaveOneToo();
} while (--numTimesToRunWhile > 0);
}
}

public static void IllHaveADuffYouHaveOneToo()
{
System.out.println();
}
}


MyEclipse 8.5 shows two errors at the semicolon immediately before "Great C hack...":
Multiple markers at this line
- Syntax error, insert "while ( Expression ) ;" to complete DoStatement
- Syntax error, insert "}" to complete Block

No comments:

Post a Comment