5 ms·
While we're discussing abuse of switch, here's my personal best effort at misusing this feature, from over thirty years ago. /* * A program to print The T
by rootbear 10y ago
While we're discussing abuse of switch, here's my personal best effort at misusing this feature, from over thirty years ago.
/*
* A program to print The Twelve Days of Christmas
* using the C fall through case statement.
*
* Jim Williams, jim@maryland, 2 May 1986 (but first written ca. 1981)
*/
/*
* If you have an ANSI compatible terminal then
* #define ANSITTY. It makes the five Golden rings
* especially tacky.
*/
#include <stdio.h>
char *day_name[] = {
"",
"first",
"second",
"third",
"fourth",
"fifth",
"sixth",
"seventh",
"eighth",
"ninth",
"tenth",
"eleventh",
"twelfth"
};
int
main()
{
int day;
printf("The Twelve Days of Christmas.\n\n");
for (day = 1; day <= 12; day++) {
printf("On the %s day of Christmas, my true love gave to me\n",
day_name[day]);
switch (day) {
case 12:
printf("\tTwelve drummers drumming,\n");
case 11:
printf("\tEleven lords a leaping,\n");
case 10:
printf("\tTen ladies dancing,\n");
case 9:
printf("\tNine pipers piping,\n");
case 8:
printf("\tEight maids a milking,\n");
case 7:
printf("\tSeven swans a swimming,\n");
case 6:
printf("\tSix geese a laying,\n");
case 5:
#ifdef ANSITTY
printf("\tFive ^[[1;5;7mGolden^[[0m rings,\n");
#else
printf("\tFive Golden rings,\n");
#endif
case 4:
printf("\tFour calling birds,\n");
case 3:
printf("\tThree French hens,\n");
case 2:
printf("\tTwo turtle doves, and\n");
case 1:
printf("\tA partridge in a pear tree.\n\n");
}
}
return 0;
}
- seishun 10y agoThis is hardly abuse. This is exactly how fallthrough was intended to be used.
- Tarean 10y agoI mean, an array could have worked but I think this is more readable than a clever version would have been. main = mapM_ putStrLn $ reverse verses where verses = combine <$> enumeratedSlices songLines combine (i, s) = "On the %s day of Christmas, my true love gave to me\n%s" % dayNames !! i $ concat s enumeratedSlices = zip [0..] . init . tails
- jcoffland 10y agoThat is abusive. You started counting from one not zero.
- rootbear 10y agoYeah, well, I was young and inexperienced... my first programming languages were BASIC and FORTRAN...