Duff's Device in C#

by Mwwhited 29. April 2009 02:04

One of the features that are "lost" in C# from C/C++ is the ability for switch cases to "fall though".  This feature may be explicitly added back to your code simple by using a "goto" pointed to a particular case.  Another way to implement this would be to use unsafe code and use pointers instead of array indexers.



public static void DuffsDevice(T[] from, T[] to)
{
    int count = from.Length;
    int position = 0;

    switch ( count % 8 )
    {
        case 0:
            to[position] = from[position++];
            goto case 7;
        case 7:
            to[position] = from[position++];
            goto case 6;
        case 6:
            to[position] = from[position++];
            goto case 5;
        case 5:
            to[position] = from[position++];
            goto case 4;
        case 4:
            to[position] = from[position++];
            goto case 3;
        case 3:
            to[position] = from[position++];
            goto case 2;
        case 2:
            to[position] = from[position++];
            goto case 1;
        case 1:
            to[position] = from[position++];
            if ( ( count -= 8 ) > 0 ) 
                goto case 0; 
            else 
                break;
    }
}

Tags:

Programming

Comments are closed

Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen

RecentPosts

Badges