🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4709

Re: integral types in switch expressions

#4709
From: Mark Brader
Date: Fri, 26 Jan 1996 22:05
50 lines
1993 bytes
Konrad Schwarz (schwarz@mips.complang.tuwien.ac.at) writes:
> I was surprised to learn that constant pointer expressions are
> not allowed in case labels and that the expression in a switch statement
> must be an integral type.  ...
> 
> Consider:
> T a [] = { ... } ...
> switch (c) {
> 	case a: ...
> 	case a + 1: ...
> 	case a + 3: ...
> 	default: ...
> }
> where T is some type.

I don't know what was in the Committee's minds, but I can point out
that this code contains constant pointer expressions only when a[]
has static storage duration.  Therefore, without extending the switch
statement to support case-expressions that would have to be computed
at run time, you would have a construct that would be useful for some
pointer values but not others.

> I am of course aware that
> switch (c - a) {
> 	case 0: ...
> 	case 1: ...
> 	case 3: ...
> 	default: ...
> }
> is equivalent code, but it suffers from the division needed to evaluate
> c - a.

No, unfortunately, it isn't.  The first one, if it worked at all, would
work for *any* value c of appropriate type.  In the second one, c must
point to an element of a[], or one past the last element.  But the
overhead of division, at least, is a red herring given a suitable
optimizer, as the code can simply be compiled as if it read:

  switch ((char *) c - (char *) a) {
  	case 0 * sizeof *a: ...
  	case 1 * sizeof *a: ...
  	case 3 * sizeof *a: ...
  	default: ...
  }

-- 
Mark Brader, msb@sq.com        "do right; have fun; make money"
SoftQuad Inc., Toronto              -- Ian Darwin on Yuri Rubinski (1952-96)

My text in this article is in the public domain.
Technical Details
Message-ID: <1996Jan26.220546.22346@sq.com>
Path: arc1-ca.pugleaf.net!nntp.coast.net!torn!sq!msb
References: <4eb5r1$b04@news.tuwien.ac.at>

Show Full Headers
Complete Article Headers
Newsgroups: comp.std.c
Path: arc1-ca.pugleaf.net!nntp.coast.net!torn!sq!msb
From: msb@sq.com (Mark Brader)
Subject: Re: integral types in switch expressions
Message-ID: <1996Jan26.220546.22346@sq.com>
Organization: SoftQuad Inc., Toronto, Canada
References: <4eb5r1$b04@news.tuwien.ac.at>
Date: Fri, 26 Jan 1996 22:05:46 GMT