Duff's original code has a bug (8 times...)
Here is a complete working program in C [ ../c/duff.c ] that uses this device to copy integer arrays.
What changes must you make to move from C to C++?
Notice that it uses a C function header that expects you to provide the address of two arrays: write a main program that lets you test it.
Publish your working C++ code and link it to a lab page explaining what is good and bad about Duff's device.
By the way, people
[ search?q=%22duff%27s+device%22&start=0&scoring=d&hl=en&lr=&safe=off&num=10 ]
are still discussing this trick.
Jackson's Inversion
Here is the design of a co-function that accepts a series of
integers and detects the first and later occurence of the number 2:
string fun(int i)
{
restart();
while( i != 2)
{
resume "no two yet";
}
resume "two";
while(true)
{
resume("there was a two");
}
}Unfortunately the above uses restart() and resume() which are nonstandard C++ functions. Resume exits a function but remembers where it was, and restart goes to that place the next time the function is call. So here is a sample test run
| i | returned value |
|---|---|
| 1 | no two yet |
| 3 | no two yet |
| 2 | two |
| 1 | there was a two |
| 2 | there was a two |
| 3 | there was a two |
Here is a file that shows it coded in standard C++. Download, compile, run and test... [ ../restart.cpp ] Download, compile, and test (99 is the terminating sentinal for input...). If you have time you can try changing it...
Add to your web page a comment on this style of "inverted code" plus
a link to an example.
Evil C Macros to make Co-Routines
Co-routines are an alternative way of getting the same effect as Jackson's
inverted code. Here
[ coroutines.html ]
is a link into a way to get the same effect in C by using some possible
dangerous macros. It also has a good discussion of why we need
co-routines.
Check the Preparation for next class
[ ../10.html ]