Google Groups Home
Help | Sign in
Message from discussion Explanation, please!
The group you are posting to is a Usenet group. Messages posted to this group will make your email address visible to anyone on the Internet.
Your reply message has not been sent.
Your post was successful
Chris Torek  
View profile
 More options Aug 25 1988, 3:16 am
Newsgroups: comp.lang.c
From: ch...@mimsy.UUCP (Chris Torek)
Date: 25 Aug 88 07:16:15 GMT
Local: Thurs, Aug 25 1988 3:16 am
Subject: Re: Explanation, please!
In article <6...@paris.ICS.UCI.EDU> schm...@bonnie.ics.uci.edu (Douglas

C. Schmidt) writes:
>The following piece of wonderful obscurity comes from Stroustup's
>C++ Programming Language book, page 100:
>   switch(count % 8) {
>      case 0:  do { *to++ = *from++;
>      case 7:       *to++ = *from++;
        ...
>      case 1:       *to++ = *from++;
>               } while (--n > 0);
>   }
>Now, much to my surprise, this is not only valid C++, it is also valid C!
>Could some one please explain to me why this is so?  It seems like
>the case 7-1 labels are actually nested inside the do {} while loop,
>and thus not in the scope of the switch (should a break statement exit
>both the switch and the loop, or just one?!?!).

`break' exits the innermost switch or loop, hence a `break' in cases
7 through 1 exits the do-while, not the switch.

>Finally, Stroustrup asks the rhetorical question ``why would anyone
>want to write something like this.''  Any guesses?!

This has been called `Duff's device' (after Tom Duff, who probably did
not invent it first), and it looks exactly like what an optimising
compiler generates when it does loop unrolling.  It works because case
labels are just that---labels.  As long as there is a switch in
scope, a case label is legal; the case applies to the closest switch.
(And if C had used a separate keyword for `break switch', the whole
thing could be consistent :-) .)

Why?  To quote a certain infamous C language hack :-) , `It looks exactly
like what an optimising compiler generates when it does loop unrolling.'

Incidentally, there are some compilers that choke on that form.  I
would have to look hard at the dpANS to decide whether it is Officially
Legal.
--
In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163)
Domain: ch...@mimsy.umd.edu      Path:   uunet!mimsy!chris


    Reply to author    Forward  
You must Sign in before you can post messages.
To post a message you must first join this group.
Please update your nickname on the subscription settings page before posting.
You do not have the permission required to post.

Create a group - Google Groups - Google Home - Terms of Service - Privacy Policy
©2008 Google