LinuxSA Mailing list archives

Index: [thread] [date] [subject] [author] [stats]
  From: Glen Turner <glen.turner@aarnet.edu.au>
  To  : Jake Hawkes <jakehawkes2001@yahoo.com>
  Date: Thu, 29 Nov 2001 10:51:40 +1030

Re: strange C code

Michael Wardle wrote:
> 
> > #include <stdio.h>
> >
> > void main(void)
> > {
> >         switch(1)
> >         {
> >         default:
> >                 printf("default");
> >         case 2:
> >                 printf("2\n");
> >                 break;
> >         case 1:
> >                 printf("1\n");
> >                 break;
> >         }
> > }
> >
> >
> > waddaya reckon the output would be?
> 
> I think the thing of interest here is supposed to be the inclusion of
> the "default" case at the first case, whereas it is traditionally listed
> last.  C seems to do the logical thing here and do case 1, but other
> languages (such as Ada) may have different results for equivalent code.

It's the logical thing if you are used to compiled languages.
People used to interpreted languages would expect the "default"
option to be executed.

The Principle of Least Surprise implies that "default" is
listed last, as is the case in every coding standard I
know of.

The sematics of the "default" label in a "switch" statement are

   [#5] The integer promotions are performed on the controlling
   expression.  The constant expression in each case  label  is
   converted   to   the   promoted   type  of  the  controlling
   expression.  If  a  converted  value  matches  that  of  the
   promoted   controlling  expression,  control  jumps  to  the
   statement following the matched case label.   Otherwise,  if
   there  is  a  default  label,  control  jumps to the labeled
   statement.  If no converted case constant expression matches
   and there is no default label, no part of the switch body is
   executed.

Note that the treatment of the "case" as a "goto" label
is unusual.  Most other languages use the Pascal-style
CASE where there is no fallthrough.

The code is particularly dangerous because of the unmarked
fallthrough on the default option -- a value other than
1 or 2 would output
  default
  2
Most lint C code style checkers would pick this up.

-- 
 Glen Turner                                 Network Engineer
 (08) 8303 3936      Australian Academic and Research Network
 glen.turner@aarnet.edu.au          http://www.aarnet.edu.au/
--
 The revolution will not be televised, it will be digitised

-- 
LinuxSA WWW: http://www.linuxsa.org.au/  IRC: #linuxsa on irc.linux.org.au
To unsubscribe from the LinuxSA list:
  mail linuxsa-request@linuxsa.org.au with "unsubscribe" as the subject


Index: [thread] [date] [subject] [author] [stats]
Return to the LinuxSA Mailing List Information Page