🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

412 total messages Page 1 of 9 Started by Lawrence D’Oliveiro Sat, 10 Oct 2026 00:25
Page 1 of 9 • 412 total messages
Re: Taming The Switch-Statement
#97
Author: Lawrence D’Oliveiro
Date: Sat, 10 Oct 2026 00:25
74 lines
4380 bytes
For comparison, here is an example of Python’s match-statement. Like
all the good (i.e. non-C-based) designs, the designers saw no point in
having fall-through.

This is a very simple example, involving straight matching of values
against instances of an enum. There are also more complex
pattern-matching options available.

    for b in sb :
        self.chars_seen.append(b)
        match self.parse_state :
            case PARSE_STATE.EXPECT_LEN :
                if ord("0") <= b <= ord("9") :
                    digit = b - ord("0")
                    if digit == 0 and len(self.chars_seen) == 2 and self.len == 0 :
                        raise NetstringSyntaxError \
                          (
                                "length must not have leading zero: %s"
                            %
                                bytes(self.chars_seen).decode()
                          )
                    #end if
                    if (
                            self.len > MAX_NETSTRING_LEN // 10
                        or
                                self.len == MAX_NETSTRING_LEN // 10
                            and
                                digit > MAX_NETSTRING_LEN % 10
                    ) :
                        raise NetstringSyntaxError \
                            ("length too large: %s" % bytes(self.chars_seen).decode())
                    #end if
                    self.len = self.len * 10 + digit
                elif b == ord(":") :
                    if len(self.chars_seen) < 2 :
                        raise NetstringSyntaxError \
                            ("missing length prefix: %s" % repr(bytes(self.chars_seen)))
                    #end if
                    if self.len != 0 :
                        self.parse_state = PARSE_STATE.EXPECT_CHARS
                    else :
                        self.parse_state = PARSE_STATE.EXPECT_END
                    #end if
                    self.content = []
                else :
                    raise NetstringSyntaxError \
                      (
                            "expecting digits of length or colon: %s"
                        %
                            repr(bytes(self.chars_seen))
                      )
                #end if
            #end case
            case PARSE_STATE.EXPECT_CHARS :
                self.content.append(b)
                self.len -= 1
                if self.len == 0 :
                    self.parse_state = PARSE_STATE.EXPECT_END
                #end if
            #end case
            case PARSE_STATE.EXPECT_END :
                if b == ord(",") :
                    self.parse_state = PARSE_STATE.PARSE_DONE
                else :
                    raise NetstringSyntaxError \
                        ("expecting comma after netstring: %s" % repr(bytes(self.chars_seen)))
                #end if
            #end case
            case PARSE_STATE.PARSE_DONE :
                raise NetstringSyntaxError \
                    ("junk after complete netstring: %s" % repr(bytes(self.chars_seen)))
            #end case
        #end match
    #end for
Re: Taming The Switch-Statement
#98
Author: bart
Date: Sat, 10 Oct 2026 00:58
38 lines
2566 bytes
On 10/10/2026 01:25, Lawrence D’Oliveiro wrote:
> For comparison, here is an example of Python’s match-statement. Like
> all the good (i.e. non-C-based) designs, the designers saw no point in
> having fall-through.

C, doesn't specifically have fallthrough. It's just that C's switch is 
so bizarre, 'fallthrough' is a consequence of it being so dumb it 
doesn't know it's still inside a switch statement; it is just code that 
it carries ploughing through until it hits more control flow.


> This is a very simple example, involving straight matching of values
> against instances of an enum. There are also more complex
> pattern-matching options available.
> 
>      for b in sb :
>          self.chars_seen.append(b)
>          match self.parse_state :

I think Python 'match' is just linear testing (I didn't notice any 
speed-ups when I tried it).

Real 'switch' allows for a jump-table and O(1) parallel matching against 
N unique possibilities.

>              case PARSE_STATE.EXPECT_LEN :

A jump-table would need all these expressions to be known at 
compile-time, and to be immutable. (This is why Python can't have nice 
things.)

>                  if ord("0") <= b <= ord("9") :

Why not:

     if b in digits:              # digits is range(ord("0"), ord("9")+1)

Re: Taming The Switch-Statement
#99
Author: Keith Thompson
Date: Sat, 10 Oct 2026 02:17
46 lines
3386 bytes
bart <bc@freeuk.com> writes:
> On 10/10/2026 01:25, Lawrence D’Oliveiro wrote:
>> For comparison, here is an example of Python’s match-statement. Like
>> all the good (i.e. non-C-based) designs, the designers saw no point in
>> having fall-through.
>
> C, doesn't specifically have fallthrough. It's just that C's switch is
> so bizarre, 'fallthrough' is a consequence of it being so dumb it
> doesn't know it's still inside a switch statement; it is just code
> that it carries ploughing through until it hits more control flow.

C's switch statement is essentially a computed goto.  It goes back
to BCPL (1967), which had different syntax (SWITCHON, CASE, ENDCASE)
but similar semantics.  BCPL's predecessor, CPL, had a more explicit
computed goto that could be used in the same way; the target of a
"go to" could be a label expression.

Think of C's "switch", not as an inferior version of Pascal's case
statement, but as an improved version of a computed goto.

The ANSI C Rationale says "No serious consideration was given to
making the switch more structured, as in Pascal, out of fear of
invalidating working code".

I suppose some version of C could have defined a new switch-like
statement without the fallthrough behavior.  I can see some small
advantages in doing so, but the existing switch with fallthrough
would have to be kept in the language -- and such a new switch-like
statement would have added no real expressive power.  We'd now have
a mix of code using the old and new constructs, pressure to convert
existing working code, and probably errors introduced by converting
code incorrectly.

Anything you could do with a more structured switch-like statement can
be done, with just a little care, with the existing switch statement.

Yes, you have to remember to write "break;" at the end of each case.

I haven't seen any proposals to add such a feature -- probably
because nobody else is as angry about it as you are.

[...]

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Re: Taming The Switch-Statement
#104
Author: bart
Date: Sat, 10 Oct 2026 10:53
159 lines
6599 bytes
On 10/10/2026 03:17, Keith Thompson wrote:
> bart <bc@freeuk.com> writes:
>> On 10/10/2026 01:25, Lawrence D’Oliveiro wrote:
>>> For comparison, here is an example of Python’s match-statement. Like
>>> all the good (i.e. non-C-based) designs, the designers saw no point in
>>> having fall-through.
>>
>> C, doesn't specifically have fallthrough. It's just that C's switch is
>> so bizarre, 'fallthrough' is a consequence of it being so dumb it
>> doesn't know it's still inside a switch statement; it is just code
>> that it carries ploughing through until it hits more control flow.
> 
> C's switch statement is essentially a computed goto.  It goes back
> to BCPL (1967), which had different syntax (SWITCHON, CASE, ENDCASE)
> but similar semantics.  BCPL's predecessor, CPL, had a more explicit
> computed goto that could be used in the same way; the target of a
> "go to" could be a label expression.
> 
> Think of C's "switch", not as an inferior version of Pascal's case
> statement, but as an improved version of a computed goto.

It's not that great as computed goto either. That tended to look like this:

    goto (L1, L2, L3) index

But C's switch index need not have consecutive values from 0 to N-1 or 1 
to N. This C switch statement (when I first wrote it I'd forgotten the 
breaks!):


     switch (a) {
     case 3: case 5:
         b = 100;
         break;

     case 2:
         b = 200;
         break;

     default:
         b = 300;
     }

Corresponds to this explicit jump-table using using gnu extensions for 
label pointers:

     void* jumptable[] = {&&def, &&def, &&case2, &&case35, &&def, &&case35};

     if (a>=0 && a<=5)
         goto *jumptable[a];
     else
         goto def;

     case35:
         b = 100;
         goto next;

     case2:
         b = 200;
         goto next;

     def:
         b = 300;
     next:

(Or it can correspond, since a compiler may choose other strategies.)

And, these days 'computed goto' in C tends to means something specific, 
which is a kind of looping switch but using multiple dispatch points 
(each break has its own goto *jumptable) rather the regular switch's one 
at the start).

The other day I posted this example from lua.c:

     vmcase(OP_ADDK) {
         op_arithK(L, l_addi, luai_numadd);
         vmbreak;
       }

vmcase and vmbreak are macros that either expand to 'case' and 'break', 
or to normal labels and goto *jumptable when gnuC is detected.

(Of, course, my language has it all:

     []ref label jumptable = (L1, L2, L3)  # first class labels

     goto (index | L1, L2, L3 | Ldef)      # 'computed goto'

     switch index when... else... end      # proper structured switch

     doswitch index...                     # looping version

     doswitchx index                       # multiple dispatch points

(So regular switch can be changed to full multi-dispatch points by 
adding that 'x'.)

But then, mine's a lower level systems language where I can consider 
such things fundamental. C is obviously higher level!)


> The ANSI C Rationale says "No serious consideration was given to
> making the switch more structured, as in Pascal, out of fear of
> invalidating working code".
> 
> I suppose some version of C could have defined a new switch-like
> statement without the fallthrough behavior.  I can see some small
> advantages in doing so, but the existing switch with fallthrough
> would have to be kept in the language -- and such a new switch-like
> statement would have added no real expressive power.  We'd now have
> a mix of code using the old and new constructs, pressure to convert
> existing working code, and probably errors introduced by converting
> code incorrectly.

I guess the same rationale means it is stuck with for(;;) loops?

That hasn't stop C++ having a higher level version.

Yet C23 has multiple ways of specifying a 32-bit integer type:

    int
    int32_t
    long        (on some platforms)
    _BitInt(32)


> Anything you could do with a more structured switch-like statement can
> be done, with just a little care, with the existing switch statement.

With a LOT more care, and with too much flexibility making it too easy 
to get things wrong. You even have this:

    case 10: default: case 20:

While if you want to do that multi-dispatch point stuff like the Lua 
example:

* You need to rewrite a normal switch into that ugly form

* There must be conditional macros somewhere to set them according
   to compiler

* A table of labels must be maintained that /exactly corresponds/ to the
   enumerations used for the index

* It doesn't work in standard C so you must use extensions

> Yes, you have to remember to write "break;" at the end of each case.
> 
> I haven't seen any proposals to add such a feature -- probably
> because nobody else is as angry about it as you are.

I'm angry because it was SO EASY to get right in the first place 
(Algol68 and Pascal already existed), and nearly as easy to fix even 
within the intervening decades.

It could also be easy to implement as structured switch can be syntactic 
sugar for an if-else-if chain.
Re: Taming The Switch-Statement
#105
Author: Janis Papanagnou
Date: Sat, 10 Oct 2026 12:01
52 lines
3777 bytes
On 2026-10-10 12:53, bart wrote:
> On 10/10/2026 03:17, Keith Thompson wrote:
[...]
>> Yes, you have to remember to write "break;" at the end of each case.
>>
>> I haven't seen any proposals to add such a feature -- probably
>> because nobody else is as angry about it as you are.
> 
> I'm angry because it was SO EASY to get right in the first place 
> (Algol68 and Pascal already existed), and nearly as easy to fix even 
> within the intervening decades.

The C-folks had other design criteria than the Pascal or Algol 68
people; the latter two have also fundamental different concepts in
their respective language (also concerning their 'case' construct).
(Specifically the Algol 68 'case' isn't very progressive, being
restricted to - even implicit! - integer tags from 1 to some N.)

I think the problem with your statement is also that you think your
preferred construct is the only one that is "right". (You seem to
be confident that supporting "fall-though" is generally "wrong".)
Just imagine if some C-programmers wanted a fall-through semantics
but all they got would be the Pascal or Algol 68 'case' construct.

I also want to remind Kornshell's break/fall-though options in their
'case', not as bulky as 'break' but yet more punctuation characters
(that makes it, if not somewhat cryptic, at least easy to overlook).

(I'm using both options, in Shell and in "C". And I cannot do that
[as simply as in "C"] in Pascal or Algol 68, where I then [have to]
use other code patterns.)

Whichever language; they have design principles. Buy them or switch.
(Unintended "switch" pun.)

You may blame the respective language if you have problems with it.
But I have a general (and well meant) suggestion for you...
If you notice that you are doing specific mistakes repeatedly - and
where you cannot change "the environment" of your mistake! - train
your awareness! (That's more successful a strategy than persistent
whining about it; i.e. if you're interested to get your tasks done.)

Janis

PS (disclaimer): That all said, I still think the approach in "C" is
a low level pattern. In other programming language I'm using their
respective patterns within their language design principles. - Some
minimum mental _flexibility_ is certainly required from programmers
if they want to (or have to) use different types of languages.

> [...]
Re: Taming The Switch-Statement
#106
Author: bart
Date: Sat, 10 Oct 2026 13:11
101 lines
5394 bytes
On 10/10/2026 13:01, Janis Papanagnou wrote:
> On 2026-10-10 12:53, bart wrote:
>> On 10/10/2026 03:17, Keith Thompson wrote:
> [...]
>>> Yes, you have to remember to write "break;" at the end of each case.
>>>
>>> I haven't seen any proposals to add such a feature -- probably
>>> because nobody else is as angry about it as you are.
>>
>> I'm angry because it was SO EASY to get right in the first place 
>> (Algol68 and Pascal already existed), and nearly as easy to fix even 
>> within the intervening decades.
> 
> The C-folks had other design criteria than the Pascal or Algol 68
> people; the latter two have also fundamental different concepts in
> their respective language (also concerning their 'case' construct).
> (Specifically the Algol 68 'case' isn't very progressive, being
> restricted to - even implicit! - integer tags from 1 to some N.)

I forgot the A68 version wasn't quite the same. But both will have a 
properly structured form, where the aim is execute one of N possible 
blocks. After executing that block, control escapes the enclosing statement.

The C aim is to pass control to one of N possible locations, but there 
are virtually no rules about where those locations can be within the 
statement following 'switch()', and it doesn't care what happens from 
then on.


> I think the problem with your statement is also that you think your
> preferred construct is the only one that is "right". (You seem to
> be confident that supporting "fall-though" is generally "wrong".)

Yes. Why, you think that fall-through is right AND should be the default 
behaviour?

If you look at actual C codebases, fall-through is incredibly rare. 
Nearly always, it will use break, or sometimes other control-flow such 
as return or goto, so that fall-through doesn't happen.

Note that if-statement blocks don't have fall-through either when there 
is an else branch. Imagine having to write this:

    if (cond) {
       statement;
       break;
    } else {
       statement;
    }

because C was crazy enough to fall through to the else block unless 
'break' was added!

I guess everyone would still defend that choice (because for one person 
in a million it will be valuable feature). But it is CLEARLY wrong.


> Just imagine if some C-programmers wanted a fall-through semantics
> but all they got would be the Pascal or Algol 68 'case' construct.

Well, Algol 68 doesn't even have 'break'. For unusual control-flow it 
needs goto.

I don't have fall-through either; it is just so rare. But I do have a 
'recase' statement to pass control to an /arbitrary/ block, not just the 
one that happens to follow.

This way, BLOCKS CAN BE REORDERED without changing behaviour.

This is an important point: a switch statement where every case block 
ends with 'break', can have those case blocks appear in any order. Or 
new ones can be inserted anywhere. Blocks commented out, deleted etc etc.

But that all goes out the window as soon as fall-through is used.

> You may blame the respective language if you have problems with it.
> But I have a general (and well meant) suggestion for you...
> If you notice that you are doing specific mistakes repeatedly - and
> where you cannot change "the environment" of your mistake! - train
> your awareness! (That's more successful a strategy than persistent
> whining about it; i.e. if you're interested to get your tasks done.)
> 
> Janis
> 
> PS (disclaimer): That all said, I still think the approach in "C" is
> a low level pattern.

The kind of structured switch I favour is still low level! After all it 
basically a jump.

It is not the structural or parametric kind of pattern matching you find 
in Rust etc.

But C's switch is just /too/ low-level. For example, a structured switch 
could be easily transformed into an if-else chain.

You can't do that in general with C switch because there IS no 
structure; it can be totally chaotic.


Re: Taming The Switch-Statement
#107
Author: Kenny McCormack
Date: Sat, 10 Oct 2026 13:14
30 lines
2463 bytes
In article <11ac783$1bkuo$1@kst.eternal-september.org>,
Keith Thompson  <Keith.S.Thompson+u@gmail.com> wrote:
...
>The ANSI C Rationale says "No serious consideration was given to
>making the switch more structured, as in Pascal, out of fear of
>invalidating working code".
>
>I suppose some version of C could have defined a new switch-like
>statement without the fallthrough behavior.  I can see some small
>advantages in doing so, but the existing switch with fallthrough
>would have to be kept in the language -- and such a new switch-like
>statement would have added no real expressive power.  We'd now have
>a mix of code using the old and new constructs, pressure to convert
>existing working code, and probably errors introduced by converting
>code incorrectly.

You are probably right that C itself will never have such a construct
added (*).  But the point is that there are many C-derived languages -
languages that use C's basic syntax (especially, using curly braces).
C++/C#/Swift - probably others.

These languages are free to have (and probably do) have better
switch/case/whatever-you-want-to-call-it constructs.

(*) Although I certainly think it would benefit from doing so.
-- 
   To be evangelical is to spend every waking moment hovering around
   two emotional states: fear and rage. Evangelicals are seriously the
   angriest and most vicious bunch of self-pitying, constantly-moaning
   whinybutts I've ever encountered.
Re: Taming The Switch-Statement
#109
Author: Johann 'Myrkraverk' Oskarsson
Date: Sat, 10 Oct 2026 13:34
26 lines
2573 bytes
On 10/10/2026 9:11 PM, bart wrote:
> because C was crazy enough to fall through to the else block unless 
> 'break' was added!
> 
> I guess everyone would still defend that choice (because for one person 
> in a million it will be valuable feature). But it is CLEARLY wrong.

It's been some years, so my memory is hazy, but the original C.P.L.
language "specification" or manual had all case: examples with an ex-
plicit return.  I'm not even sure they had thought through exactly how
the semantics were meant to work, when they figured they couldn't make a
compiler after all.

Then BCPL happened -- IIRC it happened before they had a working CPL
compiler -- and I expect that one had the fall through we're used to,
but bear in mind if you look at the most recent manual that it's not
the same compiler that predates B, and the rest is history.


You can of course ask Martin Richards, and maybe he still remembers if
the C.P.L. people had something else in mind.  Good luck.
-- 
Johann | email: invalid -> com | http://www.myrkraverk.com/blog/
I'm not from the Internet, I just work there. | via Easynews.com
https://bsky.app/profile/myrkraverk.bsky.social | for ( ;; ) _:;
Federated at https://fed.brid.gy/bsky/myrkraverk.bsky.social
Re: Taming The Switch-Statement
#110
Author: Johann 'Myrkraverk' Oskarsson
Date: Sat, 10 Oct 2026 13:58
36 lines
2902 bytes
On 10/10/2026 9:34 PM, Johann 'Myrkraverk' Oskarsson wrote:
> On 10/10/2026 9:11 PM, bart wrote:
>> because C was crazy enough to fall through to the else block unless 
>> 'break' was added!
>>
>> I guess everyone would still defend that choice (because for one 
>> person in a million it will be valuable feature). But it is CLEARLY 
>> wrong.
> 
> It's been some years, so my memory is hazy, but the original C.P.L.
> language "specification" or manual had all case: examples with an ex-
> plicit return.  I'm not even sure they had thought through exactly how
> the semantics were meant to work, when they figured they couldn't make a
> compiler after all.
> 
> Then BCPL happened -- IIRC it happened before they had a working CPL
> compiler -- and I expect that one had the fall through we're used to,
> but bear in mind if you look at the most recent manual that it's not
> the same compiler that predates B, and the rest is history.
> 
> 
> You can of course ask Martin Richards, and maybe he still remembers if
> the C.P.L. people had something else in mind.  Good luck.

Sort of.  My memory was a bit off.  See pages 122, and a bit onwards;
then 127 for the "definition" which to me is inconclusive.

   https://www.ancientgeek.org.uk/CPL/CPL_Working_Papers.pdf


Best wishes, and happy learning of the C.P.L. programming language.
-- 
Johann | email: invalid -> com | http://www.myrkraverk.com/blog/
I'm not from the Internet, I just work there. | via Easynews.com
https://bsky.app/profile/myrkraverk.bsky.social | for ( ;; ) _:;
Federated at https://fed.brid.gy/bsky/myrkraverk.bsky.social
Re: Taming The Switch-Statement
#111
Author: David Brown
Date: Sat, 10 Oct 2026 15:50
92 lines
6103 bytes
On 10/10/2026 15:11, bart wrote:
> On 10/10/2026 13:01, Janis Papanagnou wrote:
>> On 2026-10-10 12:53, bart wrote:
>>> On 10/10/2026 03:17, Keith Thompson wrote:
>> [...]
> 
>> I think the problem with your statement is also that you think your
>> preferred construct is the only one that is "right". (You seem to
>> be confident that supporting "fall-though" is generally "wrong".)
> 
> Yes. Why, you think that fall-through is right AND should be the default 
> behaviour?
> 
> If you look at actual C codebases, fall-through is incredibly rare. 
> Nearly always, it will use break, or sometimes other control-flow such 
> as return or goto, so that fall-through doesn't happen.
> 
Keith explained the background for C's switch.  It has its origins in a 
time when "goto" was commonly used, and it is a significant improvement 
on many uses of calculated goto.  It is not "bizarre", dangerous, or 
"dumb" - or "wrong".  It is simple /different/ from the structured 
switch/case/match construct found in many other languages.  The choice 
was made long ago, and it must be obvious to everyone that the behaviour 
could not be changed.

This makes it flexible - you can do things with C's "switch" that you 
cannot do with Pascal "case".  That means you can do some different, 
interesting and useful things - and it also means you can make some 
different and annoying mistakes.

You point out that most C code uses "switch" in a structured manner, 
with "break" rather than implicit fall-through.  That is my experience 
too.  What does that tell us?  I think it tells us two things :

1. People don't have a problem writing structured code with C's switch 
statements, using "break" as appropriate.  It works fine for that purpose.

It's fair, I think, to say that forgetting a "break" is a source of 
error found in C programming but not in languages with a more structured 
equivalent construct - but it is an error that is easily found by common 
tools, and will normally be found in testing otherwise.  "Missing break" 
bugs do make it into the wild sometimes, but I could not find evidence 
that it ranks high in the statistics.

2. C programmers would mostly also have been fine with a structured 
"switch" where each "case" had its own block and there was no 
fall-through.  There are, however, occasional exceptions and more 
complicated code.  Such use-cases would need to be handled in other ways 
if C's switch did not work as it does.  My gut feeling is that a solid 
proportion of such cases were more relevant in the old days before more 
optimising compilers - things like Duff's Device spring to mind as being 
useful long ago, but unnecessary with modern tools.



I personally would have been happier if C's switch was more structured 
and had no fall-through (obviously it would still need a way to have 
multiple cases attached to the same sub-block).  Does that mean I think 
C's switch is "wrong", or a bad design?  No, it does not.  Even if I did 
think it was wrong, would that mean that it /is/ wrong?  No, it would 
not - an opinion is not a fact.

Like a great many things in life, we can simply say that C's "switch" 
might have been a little more convenient if it had been defined in a 
different manner, and when making a new switch-like concept in a new 
language we would probably make different choices.  But it is what it 
is, and it's not hard to use it for correct code, so why make a fuss 
about it?  No amount of wailing and gnashing of teeth here is going to 
change anything.


To re-enforce another of Keith's points, it /would/ be possible to add a 
new switch-like construct to C with more structure and no fall-through. 
But it would provide very little benefit, and simply make the language 
that little bit more complicated - existing "switch" would obviously not 
be removed.

It's a different matter for other languages.  In C++, there is a lot 
that can be gained from a more powerful pattern-matching construct, so 
there is a lot of work going on to add it to the language.  But that is 
not a replacement for "switch" - it is primarily targeting class 
hierarchies (match on different types in the hierarchy), variants (safe 
union types, also known as "summation" types), and other features that 
do not have correspondence with C.  In C++ there is a lot to be gained 
here by a more powerful construct - the lack of implicit fall-through is 
a very minor detail.  For C, there would not be enough benefit - maybe 
it could be used to replace _Generic for some uses, but that's not worth 
the effort.



Re: Taming The Switch-Statement
#114
Author: Michael S
Date: Sat, 10 Oct 2026 16:50
14 lines
1879 bytes
On Fri, 09 Oct 2026 19:17:35 -0700
Keith Thompson <Keith.S.Thompson+u@gmail.com> wrote:
> 
>BCPL's predecessor, CPL,

I fully agree with your post (plus have to add that "more structured
switch" apart from new keyword(s) will need some new way to express
common handler for several cases. Ada/VHDL solution of using | would
not work in C for obvious reasons).

But for sentence above I have a nitpick. CPL is an ancestor of BCPL,
but not a predecessor. Historically BCPL was implemented before CPL. I
am not even sure that CPL was ever implemented entirely.
Re: Taming The Switch-Statement
#118
Author: Janis Papanagnou
Date: Sat, 10 Oct 2026 18:08
154 lines
7650 bytes
On 2026-10-10 15:11, bart wrote:
> On 10/10/2026 13:01, Janis Papanagnou wrote:
>>[...]
> 
> I forgot the A68 version wasn't quite the same. But both will have a 
> properly structured form, where the aim is execute one of N possible 
> blocks.

N(+1), yes. (And not "blocks", but that's a detail.)

> After executing that block, control escapes the enclosing statement.

Unless other things happen, yes.

> 
> The C aim is to pass control to one of N possible locations, but there 
> are virtually no rules about where those locations can be within the 
> statement following 'switch()', and it doesn't care what happens from 
> then on.

Yes, that's quite a mess (IMO), but that is how it's got designed.

> 
>> I think the problem with your statement is also that you think your
>> preferred construct is the only one that is "right". (You seem to
>> be confident that supporting "fall-though" is generally "wrong".)
> 
> Yes. Why, you think that fall-through is right AND should be the default 
> behaviour?

But I don't think so and haven't made any such claim.

I expressed that your view of what is "right" or "wrong" is futile,
it makes no sense, and is not more than an opinion.

I explained that lacking the features makes it necessary to emulate
it where needed. (That's an annoyance for those that want it.)

> 
> If you look at actual C codebases, fall-through is incredibly rare. 
> Nearly always, it will use break, or sometimes other control-flow such 
> as return or goto, so that fall-through doesn't happen.

I have no representative statistics, but my impression also matches
that; fall-through is certainly much rarer than the 'break' case.

In 6 C-sources in some of my directories I have 30 'switch' statements
(some nested on more than one level), and in two cases fall-throughs.
In another (non-C) place I find 40+ fall-throughs. - Not predominantly,
but it's certainly not only an exotic corner-case! - So there's reason
to support it, best without clumsy surrogate-constructs (workarounds).

> 
> Note that if-statement blocks don't have fall-through either when there 
> is an else branch.
>
> Imagine having to write this: [...]

(Slow down, cool down your brain! - It makes no sense to speak about
fall-throughs in contexts of 'if' constructs. Making up inappropriate
comparisons never lead you anywhere; I firmly suggest to try to stop
that, as to not again get another thread stray and out of focus.)

> 
> I guess everyone would still defend that choice (because for one person 
> in a million it will be valuable feature). But it is CLEARLY wrong.

Sadly you show again and confirm that it's just *you* who speaks about
"right" or "wrong" (even "clearly"), and again fall into the habit to
speak for or at least make wild guesses about "everyone".

I've shown above that I'm obviously regularly using it - and before my
post I didn't even know that fact, so it's nothing about "defending"
anything. And I've got not yet any indication - i.e. before your own
personal complaints about it - that only "one person / million" would
make good use of that feature; that's also completely implausible, and
there's many facts that support this opinion (e.g. people talking about
it, being part of coding standards, reading various explanations about
it as being a "*concept* in programming", etc.).

(Your opinions don't reflect the world, but rather just your personal
vicinity - which I fear isn't even more than the personal small bubble
you reside in.)

> 
>> Just imagine if some C-programmers wanted a fall-through semantics
>> but all they got would be the Pascal or Algol 68 'case' construct.
> 
> Well, Algol 68 doesn't even have 'break'. For unusual control-flow it 
> needs goto.

Yes. - And while "C" has 'goto' as well it also supports 'break' for
some purposes; e.g. as a loop-exit, so it makes sense to reuse that
keyword for other purposes as in 'switch' where it's been useful.

(Somewhere you thematized whether fall-through should be the default
behavior of 'switch'; for me it would make as much sense to switch
roles of the defaults in C's 'switch' to make the more common case
terser, or have explicit statements for both branch-behaviors types.
Actually I don't care much; there's more important things here that
I'd find noteworthy; see below.)

> 
> I don't have fall-through either; it is just so rare. But I do have a 
> 'recase' statement to pass control to an /arbitrary/ block, not just the 
> one that happens to follow.

(I'm not interested in your language.)

> This way, BLOCKS CAN BE REORDERED without changing behaviour.

Fine for you.

> 
> This is an important point: a switch statement where every case block 
> ends with 'break', can have those case blocks appear in any order. Or 
> new ones can be inserted anywhere. Blocks commented out, deleted etc etc.
> 
> But that all goes out the window as soon as fall-through is used.

I understand that it interferes with some of your design decisions.

>> [...]
> 
> The kind of structured switch I favour is still low level! After all it 
> basically a jump.

Well, I certainly favor sensible _abstractions_ to low-level jumps.
(Ideally the abstract language concepts are efficiently representable
by the processors; I like the basic Pascal design in that respect.)

> 
> It is not the structural or parametric kind of pattern matching you find 
> in Rust etc.

(I don't know Rust.)

> 
> But C's switch is just /too/ low-level. For example, a structured switch 
> could be easily transformed into an if-else chain.
> 
> You can't do that in general with C switch because there IS no 
> structure; it can be totally chaotic.

I recall, the disappointment I had with C's 'switch' was that it didn't
support "strings" as tags.[*] - But so what? Noting that as impossible
and carrying on, either with workarounds ('if' cascades) or switching
the language (if appropriate, possible, and worthwhile).

Janis

[*] In the GNU version of Awk - a much simpler but higher abstracted
language - you can nicely compare strings, and even regexps.
Re: Taming The Switch-Statement
#119
Author: Janis Papanagnou
Date: Sat, 10 Oct 2026 18:13
14 lines
1844 bytes
On 2026-10-10 18:50, Michael S wrote:
> 
> I fully agree with your post (plus have to add that "more structured
> switch" apart from new keyword(s) will need some new way to express
> common handler for several cases. Ada/VHDL solution of using | would
> not work in C for obvious reasons).

Pascal allows '..' and ',' (for ranges and lists), and even mixed.
That should (in principle) be a syntactical possibility in "C".

Janis

> [...]
Re: Taming The Switch-Statement
#121
Author: Michael S
Date: Sat, 10 Oct 2026 19:02
18 lines
2112 bytes
On Sat, 10 Oct 2026 20:08:20 +0200
Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:

> On 2026-10-10 15:11, bart wrote:
> > 
> > Well, Algol 68 doesn't even have 'break'. For unusual control-flow
> > it needs goto.  
> 
> Yes. - And while "C" has 'goto' as well it also supports 'break' for
> some purposes; e.g. as a loop-exit, so it makes sense to reuse that
> keyword for other purposes as in 'switch' where it's been useful.
>

After practicing C programming for more than 35 years I am deeply
convinced that reuse of the same 'break' keyword for loops and for
switch was a mistake. But then again, DRM did not have a benefit
of hindsight.
Re: Taming The Switch-Statement
#123
Author: Dan Cross
Date: Sat, 10 Oct 2026 19:03
24 lines
1782 bytes
In article <20261010220212.000063fd@yahoo.com>,
Michael S  <already5chosen@yahoo.com> wrote:
>On Sat, 10 Oct 2026 20:08:20 +0200
>Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
>
>> On 2026-10-10 15:11, bart wrote:
>> > 
>> > Well, Algol 68 doesn't even have 'break'. For unusual control-flow
>> > it needs goto.  
>> 
>> Yes. - And while "C" has 'goto' as well it also supports 'break' for
>> some purposes; e.g. as a loop-exit, so it makes sense to reuse that
>> keyword for other purposes as in 'switch' where it's been useful.
>>
>
>After practicing C programming for more than 35 years I am deeply
>convinced that reuse of the same 'break' keyword for loops and for
>switch was a mistake. But then again, DRM did not have a benefit
>of hindsight.

Perhaps you mean "DMR", aka, Dennis Ritchie.

	- Dan C.
Re: Taming The Switch-Statement
#122
Author: Michael S
Date: Sat, 10 Oct 2026 19:29
30 lines
2350 bytes
On Sat, 10 Oct 2026 19:03:59 -0000 (UTC)
cross@spitfire.i.gajendra.net (Dan Cross) wrote:

> In article <20261010220212.000063fd@yahoo.com>,
> Michael S  <already5chosen@yahoo.com> wrote:
> >On Sat, 10 Oct 2026 20:08:20 +0200
> >Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
> >  
> >> On 2026-10-10 15:11, bart wrote:  
> >> > 
> >> > Well, Algol 68 doesn't even have 'break'. For unusual
> >> > control-flow it needs goto.    
> >> 
> >> Yes. - And while "C" has 'goto' as well it also supports 'break'
> >> for some purposes; e.g. as a loop-exit, so it makes sense to reuse
> >> that keyword for other purposes as in 'switch' where it's been
> >> useful. 
> >
> >After practicing C programming for more than 35 years I am deeply
> >convinced that reuse of the same 'break' keyword for loops and for
> >switch was a mistake. But then again, DRM did not have a benefit
> >of hindsight.  
> 
> Perhaps you mean "DMR", aka, Dennis Ritchie.
> 
> 	- Dan C.
> 

Yes, thank you.
Re: Taming The Switch-Statement
#125
Author: Janis Papanagnou
Date: Sat, 10 Oct 2026 19:55
24 lines
2571 bytes
On 2026-10-10 21:02, Michael S wrote:
> On Sat, 10 Oct 2026 20:08:20 +0200
> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
> 
>> Yes. - And while "C" has 'goto' as well it also supports 'break' for
>> some purposes; e.g. as a loop-exit, so it makes sense to reuse that
>> keyword for other purposes as in 'switch' where it's been useful.
> 
> After practicing C programming for more than 35 years I am deeply
> convinced that reuse of the same 'break' keyword for loops and for
> switch was a mistake. [...]

Well, I think the principal design criticism that bart made had a
stronger impact on the "C" language design than the profane re-use
of the 'break' keyword. My impression is that most languages try to
minimize the amount of keywords. (The extreme scarcity of keywords
in "C" and the syntactical consequences is actually something I
rather don't really like with C-like languages.)

But I got curious about what your concrete reasons for that deeply
conviction are; in which way was it a "mistake"?

Janis
Re: Taming The Switch-Statement
#128
Author: Michael S
Date: Sat, 10 Oct 2026 20:03
33 lines
2832 bytes
On Sat, 10 Oct 2026 21:55:04 +0200
Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:

> On 2026-10-10 21:02, Michael S wrote:
> > On Sat, 10 Oct 2026 20:08:20 +0200
> > Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
> >   
> >> Yes. - And while "C" has 'goto' as well it also supports 'break'
> >> for some purposes; e.g. as a loop-exit, so it makes sense to reuse
> >> that keyword for other purposes as in 'switch' where it's been
> >> useful.  
> > 
> > After practicing C programming for more than 35 years I am deeply
> > convinced that reuse of the same 'break' keyword for loops and for
> > switch was a mistake. [...]  
> 
> Well, I think the principal design criticism that bart made had a
> stronger impact on the "C" language design than the profane re-use
> of the 'break' keyword. My impression is that most languages try to
> minimize the amount of keywords. (The extreme scarcity of keywords
> in "C" and the syntactical consequences is actually something I
> rather don't really like with C-like languages.)
> 
> But I got curious about what your concrete reasons for that deeply
> conviction are; in which way was it a "mistake"?
> 
> Janis
> 

The cases where I want to break out of the loop from the switch in the
body of the loop are very common.

Re: Taming The Switch-Statement
#131
Author: bart
Date: Sat, 10 Oct 2026 20:09
195 lines
8543 bytes
On 10/10/2026 19:08, Janis Papanagnou wrote:
> On 2026-10-10 15:11, bart wrote:
>> On 10/10/2026 13:01, Janis Papanagnou wrote:
>>> [...]

>> If you look at actual C codebases, fall-through is incredibly rare. 
>> Nearly always, it will use break, or sometimes other control-flow such 
>> as return or goto, so that fall-through doesn't happen.
> 
> I have no representative statistics, but my impression also matches
> that; fall-through is certainly much rarer than the 'break' case.
> 
> In 6 C-sources in some of my directories I have 30 'switch' statements
> (some nested on more than one level), and in two cases fall-throughs.
> In another (non-C) place I find 40+ fall-throughs. - Not predominantly,
> but it's certainly not only an exotic corner-case! - So there's reason
> to support it, best without clumsy surrogate-constructs (workarounds).

This is difficult for me to survey as it take some effort in a compiler, 
and I no long have many C codebases around. But here is one attempt:

Program      Case Labels  Break/Goto/Return

Piet           6          6
SQLite3      793        805
Lua          555        472
Nano           9          9
TinyPas      160        118
STB           69         62
MiniGMP       13         13

Middle column is total case labels which not followed by another case label.

Right column is total number of switch-breaks, plus return/goto IF they 
are the first and only statement in the case-block. (Being unstructured 
makes it tricky.)

So Return/Goto following other code is not counted. In some cases I have 
verified that some been missed for that reason.

This is not foolproof: one case may have 2 breaks, and the following 
none so falls through. But from visual inspections failed to show 
significant fall-through in use.




>>
>> Note that if-statement blocks don't have fall-through either when 
>> there is an else branch.
>>
>> Imagine having to write this: [...]
> 
> (Slow down, cool down your brain! - It makes no sense to speak about
> fall-throughs in contexts of 'if' constructs. Making up inappropriate
> comparisons never lead you anywhere;

If it is probably the most relevant comparison that you can make.

A statement like this:

    if (cond) {A} else {B}

can be always be expressed as:

    switch (!!cond)
    case 1:  {A}; break;
    default: {B}
    }

Notice that 'break' the switch needs, that 'if' doesn't.


>> I guess everyone would still defend that choice (because for one 
>> person in a million it will be valuable feature). But it is CLEARLY 
>> wrong.
> 
> Sadly you show again and confirm that it's just *you* who speaks about
> "right" or "wrong" (even "clearly"), and again fall into the habit to
> speak for or at least make wild guesses about "everyone".

> I've shown above that I'm obviously regularly using it

You haven't given an example, which would be interesting. But this is 
the curious fact about C, that after 50 years, every misfeature and 
quirk is an invaluable feature to somebody!


- and before my
> post I didn't even know that fact, so it's nothing about "defending"
> anything. And I've got not yet any indication - i.e. before your own
> personal complaints about it - that only "one person / million" would

Well, that was about fall-through in an IF statement.

> make good use of that feature; that's also completely implausible, and
> there's many facts that support this opinion (e.g. people talking about
> it, being part of coding standards, reading various explanations about
> it as being a "*concept* in programming", etc.).
> 
> (Your opinions don't reflect the world, but rather just your personal
> vicinity - which I fear isn't even more than the personal small bubble
> you reside in.)

No. Look at how 'switch' implemented in pretty much every other language 
other C (and C++ which inherited it).

How many have default fall-through?

I suggest most people have the same opinion as I do on this.

>>
>>> Just imagine if some C-programmers wanted a fall-through semantics
>>> but all they got would be the Pascal or Algol 68 'case' construct.
>>
>> Well, Algol 68 doesn't even have 'break'. For unusual control-flow it 
>> needs goto.
> 
> Yes. - And while "C" has 'goto' as well it also supports 'break' for
> some purposes; e.g. as a loop-exit, so it makes sense to reuse that
> keyword for other purposes as in 'switch' where it's been useful.

No, it makes no sense at all, because their use-cases overlap.

It means that, inside a SWITCH statement, you can't do an early break 
out of a case-block from inside a loop.

And if inside a loop, you can't break out of that loop from inside a 
switch statement:

    while (1) {
        if (x == 3)
            break;

        switch (x) {
        case 3: break;
        }
    }

The first break works within IF. But if you choose to use SWITCH, if 
doesn't work.

You still think it makes sense?

> (Somewhere you thematized whether fall-through should be the default
> behavior of 'switch'; for me it would make as much sense to switch
> roles of the defaults in C's 'switch' to make the more common case
> terser, or have explicit statements for both branch-behaviors types.
> Actually I don't care much; there's more important things here that
> I'd find noteworthy; see below.)
> 
>>
>> I don't have fall-through either; it is just so rare. But I do have a 
>> 'recase' statement to pass control to an /arbitrary/ block, not just 
>> the one that happens to follow.
> 
> (I'm not interested in your language.)

Why not? You don't have to use it; it just needs to exist.

A 'structured switch' has been discussed. And I have a 'structured 
switch' implemented in a equally low level language, so Ask Me Anything.


>> This way, BLOCKS CAN BE REORDERED without changing behaviour.
> 
> Fine for you.

It's fine for everyone.

>> But C's switch is just /too/ low-level. For example, a structured 
>> switch could be easily transformed into an if-else chain.
>>
>> You can't do that in general with C switch because there IS no 
>> structure; it can be totally chaotic.
> 
> I recall, the disappointment I had with C's 'switch' was that it didn't
> support "strings" as tags.[*] - But so what? Noting that as impossible
> and carrying on, either with workarounds ('if' cascades) or switching
> the language (if appropriate, possible, and worthwhile).
> 

> [*] In the GNU version of Awk - a much simpler but higher abstracted
> language - you can nicely compare strings, and even regexps.

I have a narrow view of SWITCH, which is specifically for use with 
integer values. That allows comparison of N unique possibilities 
simultaneously, or in O(1) time.
So if you're comparing strings, then it is not SWITCH IMO, unless those 
strings are perhaps interned.

(I use a different feature when it needs to be more flexible, and in 
that case, any type for which equality, or sometimes 'in', is defined, 
will work.)
Re: Taming The Switch-Statement
#136
Author: Janis Papanagnou
Date: Sat, 10 Oct 2026 20:33
11 lines
1952 bytes
On 2026-10-10 22:03, Michael S wrote:
> 
> The cases where I want to break out of the loop from the switch in the
> body of the loop are very common.

Ah, so you'd have needed something like Kornshell's 'break 2' to leave
more than one level. - I suppose, you needed to used a 'goto' instead
(and avoid the 'break' completely for those cases).

Janis
Re: Taming The Switch-Statement
#138
Author: bart
Date: Sat, 10 Oct 2026 20:53
14 lines
2164 bytes
On 10/10/2026 21:33, Janis Papanagnou wrote:
> On 2026-10-10 22:03, Michael S wrote:
>>
>> The cases where I want to break out of the loop from the switch in the
>> body of the loop are very common.
> 
> Ah, so you'd have needed something like Kornshell's 'break 2' to leave
> more than one level. - I suppose, you needed to used a 'goto' instead
> (and avoid the 'break' completely for those cases).
No, there is only one level of loop here. But you can't use 'break' 
because it is doing double duty as a hack to get out of the middle of a 
switch statement.

Re: Taming The Switch-Statement
#143
Author: Janis Papanagnou
Date: Sat, 10 Oct 2026 21:14
86 lines
4924 bytes
[ I skip most of what you wrote because it's not adding anything new
   and I basically still just disagree with all you presented; if you
   re-read my previous post you have my comments on your "new" text. ]

On 2026-10-10 22:09, bart wrote:
> On 10/10/2026 19:08, Janis Papanagnou wrote:
>> On 2026-10-10 15:11, bart wrote:
>>> On 10/10/2026 13:01, Janis Papanagnou wrote:
>>>>
>>>> Just imagine if some C-programmers wanted a fall-through semantics
>>>> but all they got would be the Pascal or Algol 68 'case' construct.
>>>
>>> Well, Algol 68 doesn't even have 'break'. For unusual control-flow it 
>>> needs goto.
>>
>> Yes. - And while "C" has 'goto' as well it also supports 'break' for
>> some purposes; e.g. as a loop-exit, so it makes sense to reuse that
>> keyword for other purposes as in 'switch' where it's been useful.
> 
> No, it makes no sense at all, because their use-cases overlap.
> 
> It means that, inside a SWITCH statement, you can't do an early break 
> out of a case-block from inside a loop.
> 
> And if inside a loop, you can't break out of that loop from inside a 
> switch statement:
> 
>     while (1) {
>         if (x == 3)
>             break;
> 
>         switch (x) {
>         case 3: break;
>         }
>     }
> 
> The first break works within IF. But if you choose to use SWITCH, if 
> doesn't work.

It also doesn't work in nested loops. (That's a restriction of C's
'break'.)

I don't think it makes sense to introduce another distinct keyword
to address a special case like that; that's very short-sighted. You
could still not address, e.g., a  "for() for() switch()"  structure.
Other languages provide more universal, thus more sensible features
to support out-of-band conditions, or more universal "local exits"
(that support more than one nested level).

> You still think it makes sense?

Yes, because it works as intended for the other common cases.

If you need a "flexible jump" just use 'goto'. The point of 'break'
is to "tame" that "harmful goto" and introduce something "lighter".

Some languages support a 'break' (and a 'continue') with a numeric
argument to handle the case of nested constructs. That is of course
yet more flexible without sacrificing the "prevent wild jumps" dogma.

[ another big snip ]

>> [*] In the GNU version of Awk - a much simpler but higher abstracted
>> language - you can nicely compare strings, and even regexps.
> 
> I have a narrow view of SWITCH, which is specifically for use with 
> integer values. That allows comparison of N unique possibilities 
> simultaneously, or in O(1) time.
> So if you're comparing strings, then it is not SWITCH IMO, unless those 
> strings are perhaps interned.

A CDC 175/176 carried a Pascal TEXT object in one machine word and
could compare it as atom. Newer standard PC CPUs have more bits in
a word than those former supercomputers. - But the point here was
that internals should be abstracted by a higher level programming
language. - And compilers have principally various possibilities to
support some "atomization" of string comparisons with compile-time
string constants. - As said, it would have been useful in many of
my application cases. (No more, no less.)

(BTW, it would be new to me that you'd have complexity guarantees in
"C".)

Janis

> [...]
Re: Taming The Switch-Statement
#144
Author: Janis Papanagnou
Date: Sat, 10 Oct 2026 21:16
19 lines
2353 bytes
On 2026-10-10 22:53, bart wrote:
> On 10/10/2026 21:33, Janis Papanagnou wrote:
>> On 2026-10-10 22:03, Michael S wrote:
>>>
>>> The cases where I want to break out of the loop from the switch in the
>>> body of the loop are very common.
>>
>> Ah, so you'd have needed something like Kornshell's 'break 2' to leave
>> more than one level. - I suppose, you needed to used a 'goto' instead
>> (and avoid the 'break' completely for those cases).

> No, there is only one level of loop here. But you can't use 'break' 
> because it is doing double duty as a hack to get out of the middle of a 
> switch statement.

Re-read my post and try to understand what I wrote. - Good luck!

Janis
Re: Taming The Switch-Statement
#149
Author: bart
Date: Sat, 10 Oct 2026 22:01
130 lines
6281 bytes
On 10/10/2026 22:14, Janis Papanagnou wrote:
> [ I skip most of what you wrote because it's not adding anything new
>    and I basically still just disagree with all you presented; if you
>    re-read my previous post you have my comments on your "new" text. ]
> 
> On 2026-10-10 22:09, bart wrote:
>> On 10/10/2026 19:08, Janis Papanagnou wrote:
>>> On 2026-10-10 15:11, bart wrote:
>>>> On 10/10/2026 13:01, Janis Papanagnou wrote:
>>>>>
>>>>> Just imagine if some C-programmers wanted a fall-through semantics
>>>>> but all they got would be the Pascal or Algol 68 'case' construct.
>>>>
>>>> Well, Algol 68 doesn't even have 'break'. For unusual control-flow 
>>>> it needs goto.
>>>
>>> Yes. - And while "C" has 'goto' as well it also supports 'break' for
>>> some purposes; e.g. as a loop-exit, so it makes sense to reuse that
>>> keyword for other purposes as in 'switch' where it's been useful.
>>
>> No, it makes no sense at all, because their use-cases overlap.
>>
>> It means that, inside a SWITCH statement, you can't do an early break 
>> out of a case-block from inside a loop.
>>
>> And if inside a loop, you can't break out of that loop from inside a 
>> switch statement:
>>
>>     while (1) {
>>         if (x == 3)
>>             break;
>>
>>         switch (x) {
>>         case 3: break;
>>         }
>>     }
>>
>> The first break works within IF. But if you choose to use SWITCH, if 
>> doesn't work.
> 
> It also doesn't work in nested loops. (That's a restriction of C's
> 'break'.)

That is a separate matter, and one that occurs sparingly.

On the other hand, breaking out of one level is fairly common, and so is 
the use of 'switch'.

Now you have an artificial problem caused by two brain-dead decisions:

* A crappy, crude design of 'switch' that leaves you stranded in the
   middle of the statement

* Deciding to fix that by USING THE SAME KEYWORD as one of the loop
   controls, for something that isn't to do with loops.

This is just very poor language design.

(Inside my C compiler, there are two AST tags called 'jbreak' and 
'jbreaksw' - they are two distinct features.)


> 
> I don't think it makes sense to introduce another distinct keyword
> to address a special case like that; that's very short-sighted. You
> could still not address, e.g., a  "for() for() switch()"  structure.
> Other languages provide more universal, thus more sensible features
> to support out-of-band conditions, or more universal "local exits"
> (that support more than one nested level).

THIS IS NOT A NESTED LOOP PROBLEM! It has been made into one by reusing 
BREAK.

What's the big deal about keywords anyway?


>> You still think it makes sense?
> 
> Yes, because it works as intended for the other common cases.

Would you have made the same choice?

Assuming yes, and assuming you'd also devise some scheme to cut across 
nesting, what would happen here:

    FOR
       SWITCH
          FOR
             SWITCH
                 break...

You want to break out of that inner FOR, but now you have to count both 
nested loops and switch. So, break 2?

So what would break 3 mean: does it get you to the end of that outer 
SWITCH? This is something that would not previously have cross your mind:

    SWITCH
       SWITCH
          break 2

That is, to use 'break' to cut to the end of the enclosing switch 
statements. It is just not meaningful.

This just further shows that the two concepts are distinct.



>> I have a narrow view of SWITCH, which is specifically for use with 
>> integer values. That allows comparison of N unique possibilities 
>> simultaneously, or in O(1) time.
>> So if you're comparing strings, then it is not SWITCH IMO, unless 
>> those strings are perhaps interned.
> 
> A CDC 175/176 carried a Pascal TEXT object in one machine word and
> could compare it as atom. Newer standard PC CPUs have more bits in
> a word than those former supercomputers. - But the point here was
> that internals should be abstracted by a higher level programming
> language. - And compilers have principally various possibilities to
> support some "atomization" of string comparisons with compile-time
> string constants. - As said, it would have been useful in many of
> my application cases. (No more, no less.)

My point is that SWITCH should be a low level feature working on 
integers. (Like how CASE works in Algol68.)

A version for higher level types, for runtime case-values, and a 
possible sequential, ordered search, could share the same keyword, but I 
would prefer a different keywords here since the semantics can be very 
different.
Re: Taming The Switch-Statement
#150
Author: Andrey Tarasevich
Date: Sat, 10 Oct 2026 22:30
22 lines
2562 bytes
On Sat 10/10/2026 1:33 PM, Janis Papanagnou wrote:
> On 2026-10-10 22:03, Michael S wrote:
>>
>> The cases where I want to break out of the loop from the switch in the
>> body of the loop are very common.
> 
> Ah, so you'd have needed something like Kornshell's 'break 2' to leave
> more than one level.
Yes, but that would be rather inelegant in the overall scheme of things 
in C, since once we start talking about `break 2` it would be logical to 
consider `continue 2` as well (i.e. like Kornshell's `continue`).

But `break` and `continue` behave differently inside `switch` in C: the 
former can "see" the enveloping `switch` statements, while for the 
latter all enveloping `switch` statements are completely transparent. 
So, in order to refer to the same cycle one'd have to use different 
nesting numbers in `break` and `continue` when used inside `switch`(-es) 
in C. That would look quite confusing.

-- 
Best regards,
Andrey
Re: Taming The Switch-Statement
#152
Author: Keith Thompson
Date: Sat, 10 Oct 2026 22:32
22 lines
2397 bytes
Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
> On 2026-10-10 22:03, Michael S wrote:
>> The cases where I want to break out of the loop from the switch in
>> the
>> body of the loop are very common.
>
> Ah, so you'd have needed something like Kornshell's 'break 2' to leave
> more than one level. - I suppose, you needed to used a 'goto' instead
> (and avoid the 'break' completely for those cases).

Something like that, sure, but please not that.

Specifying the *number* of levels to break or continue is IMHO
horrible.  "break N" makes me count things so the computer doesn't
have to.

There are proposals, and precedents in other languages, for *named*
loops, and I'd like to see that in a future C.

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Re: Taming The Switch-Statement
#151
Author: Keith Thompson
Date: Sat, 10 Oct 2026 22:54
44 lines
3347 bytes
Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
> On 2026-10-10 18:50, Michael S wrote:
>> I fully agree with your post (plus have to add that "more structured
>> switch" apart from new keyword(s) will need some new way to express
>> common handler for several cases. Ada/VHDL solution of using | would
>> not work in C for obvious reasons).
>
> Pascal allows '..' and ',' (for ranges and lists), and even mixed.
> That should (in principle) be a syntactical possibility in "C".

C2Y will add case ranges using "..." (which is already a token used for
variadic functions), with syntax and semantics close to the existing gcc
extension.

    switch (foo) {
        case 'a' ... 'z':
            // ...
    }

This was considered and rejected (with "..") for C89.  One reason for
rejecting it was that 'A'..'Z' is not contiguous in all character
sets (particularly not in EBCDIC).  The C89 Rationale also mentions
the problem of large code or jump table space for something like
0..65535, something that can be handled these days by minimally
clever compilers.

One problem is that `case 0...1:` is a syntax error.  0...1 is a valid
preprocessing number that can't be converted to a valid constant.
The solution is to surround the ...  with spaces, which is probably
a good idea anyway.

As for ',', that would avoid having to repeat the "case" keyword,
but it could be visually confusing.  `case 0, 1:` is currently a
syntax error, but only because a constant expression can't include
a comma operator (with some obscure exceptions).  Allowing commas
would prevent a future version of the language from either allowing
comma operators in constant expressions or permitting non-constant
expressions in case labels.  I still wouldn't mind such a change,
but it would add no real expressive power and I don't think anyone
has proposed it.

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Re: Taming The Switch-Statement
#153
Author: Lawrence D’Oliveiro
Date: Sat, 10 Oct 2026 22:58
30 lines
3235 bytes
On Sat, 10 Oct 2026 15:30:54 -0700, Andrey Tarasevich wrote:

> But `break` and `continue` behave differently inside `switch` in C:
> the former can "see" the enveloping `switch` statements, while for
> the latter all enveloping `switch` statements are completely
> transparent. So, in order to refer to the same cycle one'd have to
> use different nesting numbers in `break` and `continue` when used
> inside `switch`(-es) in C. That would look quite confusing.

It also led to a major real-world calamity: the Great AT&T Telephone
Crash of 15th January 1990. To quote from Bruce Sterling’s “The Hacker
Crackdown”:

    As it happened, the problem itself -- the problem per se -- took
    this form. A piece of telco software had been written in C
    language, a standard language of the telco field. Within the C
    software was a long "do... while" construct. The "do... while"
    construct contained a "switch" statement. The "switch" statement
    contained an "if" clause. The "if" clause contained a "break." The
    "break" was *supposed* to "break" the "if clause." Instead, the
    "break" broke the "switch" statement.

Back at the time, law enforcement was just cottoning on to the idea
that evil people could use their technical skills with computers to
wreak havoc with all kinds of crucial infrastructure. AT&T figured
out, within nine hours, that the problem here was purely a mistake in
their software, but it took somewhat longer for some authorities to be
disabused of the notion that this was intentional sabotage.

<http://web.archive.org/web/20031204221934/www.chriswaltrip.com/sterling/>
Re: Taming The Switch-Statement
#154
Author: Michael S
Date: Sat, 10 Oct 2026 22:58
27 lines
2609 bytes
On Sat, 10 Oct 2026 15:32:32 -0700
Keith Thompson <Keith.S.Thompson+u@gmail.com> wrote:

> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
> > On 2026-10-10 22:03, Michael S wrote:  
> >> The cases where I want to break out of the loop from the switch in
> >> the
> >> body of the loop are very common.  
> >
> > Ah, so you'd have needed something like Kornshell's 'break 2' to
> > leave more than one level. - I suppose, you needed to used a 'goto'
> > instead (and avoid the 'break' completely for those cases).  
> 
> Something like that, sure, but please not that.
> 
> Specifying the *number* of levels to break or continue is IMHO
> horrible.  "break N" makes me count things so the computer doesn't
> have to.
> 
> There are proposals, and precedents in other languages, for *named*
> loops, and I'd like to see that in a future C.
> 

Yes. Break n is a maintanance nightmare.
Ada syntax (optional label before loop) is a lot better.

Re: Taming The Switch-Statement
#155
Author: Keith Thompson
Date: Sat, 10 Oct 2026 23:30
109 lines
5626 bytes
bart <bc@freeuk.com> writes:
> On 10/10/2026 03:17, Keith Thompson wrote:
>> bart <bc@freeuk.com> writes:
>>> On 10/10/2026 01:25, Lawrence D’Oliveiro wrote:
>>>> For comparison, here is an example of Python’s match-statement. Like
>>>> all the good (i.e. non-C-based) designs, the designers saw no point in
>>>> having fall-through.
>>>
>>> C, doesn't specifically have fallthrough. It's just that C's switch is
>>> so bizarre, 'fallthrough' is a consequence of it being so dumb it
>>> doesn't know it's still inside a switch statement; it is just code
>>> that it carries ploughing through until it hits more control flow.
>>
>> C's switch statement is essentially a computed goto.  It goes back
>> to BCPL (1967), which had different syntax (SWITCHON, CASE, ENDCASE)
>> but similar semantics.  BCPL's predecessor, CPL, had a more explicit
>> computed goto that could be used in the same way; the target of a
>> "go to" could be a label expression.
>>
>> Think of C's "switch", not as an inferior version of Pascal's case
>> statement, but as an improved version of a computed goto.
>
> It's not that great as computed goto either. That tended to look like this:
>
>    goto (L1, L2, L3) index

BCPL's "SWITCHON" is a more structured replacement for what was probably
(I'm speculating) a major use case for CPL's "go to expr".

[...]

> And, these days 'computed goto' in C tends to means something
> specific, which is a kind of looping switch but using multiple
> dispatch points (each break has its own goto *jumptable) rather the
> regular switch's one at the start).

Huh?  "computed goto" is not a looping construct.  But C doesn't
have computed goto, so I'm not going to discuss it here other than
in the context of how C's switch statement came to be.

[...]

> (Of, course, my language has it all:

Of course it does.

[...]

>> The ANSI C Rationale says "No serious consideration was given to
>> making the switch more structured, as in Pascal, out of fear of
>> invalidating working code".
>>
>> I suppose some version of C could have defined a new switch-like
>> statement without the fallthrough behavior.  I can see some small
>> advantages in doing so, but the existing switch with fallthrough
>> would have to be kept in the language -- and such a new switch-like
>> statement would have added no real expressive power.  We'd now have
>> a mix of code using the old and new constructs, pressure to convert
>> existing working code, and probably errors introduced by converting
>> code incorrectly.
>
> I guess the same rationale means it is stuck with for(;;) loops?

Yes, of course it does.  Did you think that a construct that's used in
most existing C programs could just be removed from the language?

> That hasn't stop C++ having a higher level version.

C is not C++.  A future C could have additional looping constructs,
but I haven't seen any concrete proposals.

[...]

>> Anything you could do with a more structured switch-like statement can
>> be done, with just a little care, with the existing switch statement.
>
> With a LOT more care, and with too much flexibility making it too easy
> to get things wrong. You even have this:

No, with a little care.

>    case 10: default: case 20:

Doctor, it hurts when I do this.

[...]

>> Yes, you have to remember to write "break;" at the end of each case.
>> I haven't seen any proposals to add such a feature -- probably
>> because nobody else is as angry about it as you are.
>
> I'm angry because it was SO EASY to get right in the first place
> (Algol68 and Pascal already existed), and nearly as easy to fix even
> within the intervening decades.

You're angry about a decision that was made in the 1960s and 1970s,
and you're whining about it to people who can't do anything about it.
That can't be good for you.

I've explained why it doesn't need fixing, and would not be easy to fix.

> It could also be easy to implement as structured switch can be
> syntactic sugar for an if-else-if chain.

If you want an if-else-if chain, write an if-else-if chain.

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Re: Taming The Switch-Statement
#156
Author: Keith Thompson
Date: Sat, 10 Oct 2026 23:38
31 lines
2713 bytes
Michael S <already5chosen@yahoo.com> writes:
> On Sat, 10 Oct 2026 20:08:20 +0200
> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
>> On 2026-10-10 15:11, bart wrote:
>> > 
>> > Well, Algol 68 doesn't even have 'break'. For unusual control-flow
>> > it needs goto.  
>> 
>> Yes. - And while "C" has 'goto' as well it also supports 'break' for
>> some purposes; e.g. as a loop-exit, so it makes sense to reuse that
>> keyword for other purposes as in 'switch' where it's been useful.
>
> After practicing C programming for more than 35 years I am deeply
> convinced that reuse of the same 'break' keyword for loops and for
> switch was a mistake. But then again, DRM did not have a benefit
> of hindsight.

Actually he (DMR) did.  C's parent language, BCPL, had distinct BREAK
and ENDCASE keywords.

I agree that combining them both into "break" was a mistake.  At this
point, I think the best solution is named loops and "break loop_name;".
There are proposals for C2y.

A distinct "endcase" keyword would have been cleaner IMHO, but code
using the existing case/break will continue to exist approximately
forever.

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Re: Taming The Switch-Statement
#157
Author: Keith Thompson
Date: Sat, 10 Oct 2026 23:44
21 lines
2216 bytes
Michael S <already5chosen@yahoo.com> writes:
> On Fri, 09 Oct 2026 19:17:35 -0700
> Keith Thompson <Keith.S.Thompson+u@gmail.com> wrote:
>> 
>>BCPL's predecessor, CPL,
>
> I fully agree with your post (plus have to add that "more structured
> switch" apart from new keyword(s) will need some new way to express
> common handler for several cases. Ada/VHDL solution of using | would
> not work in C for obvious reasons).
>
> But for sentence above I have a nitpick. CPL is an ancestor of BCPL,
> but not a predecessor. Historically BCPL was implemented before CPL. I
> am not even sure that CPL was ever implemented entirely.

Interesting.  I've read some of the documents that describe CPL/BCPL/B,
but I'm not familiar with how they were actually implemented and used.

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Re: Taming The Switch-Statement
#158
Author: Keith Thompson
Date: Sat, 10 Oct 2026 23:56
33 lines
2772 bytes
Keith Thompson <Keith.S.Thompson+u@gmail.com> writes:
[...]
> C's switch statement is essentially a computed goto.  It goes back
> to BCPL (1967), which had different syntax (SWITCHON, CASE, ENDCASE)
> but similar semantics.  BCPL's predecessor, CPL, had a more explicit
> computed goto that could be used in the same way; the target of a
> "go to" could be a label expression.
[...]

I realize I skipped over an entire language.

C's immediate ancestor B had the same switch/case/break syntax as C.

Ken Thompson's B manual, from 1972, doesn't mention "break" (for
either switch statements or loops), and apparently required "goto"
to break out of a loop or switch statement.  There's a sample program
with a switch statement that uses "goto" on each case, but it jumps
to the top of a loop, not to the bottom of the switch.

Kernighan's B tutorial does use "break".  Apparently "break" was
added to the language some time after the manual was written.

B's parent BCPL had both "BREAK" and "ENDCASE".  Apparently both
were dropped when B was designed, and then only one was reintroduced.

https://www.nokia.com/bell-labs/about/dennis-m-ritchie/kbman.html
https://www.nokia.com/bell-labs/about/dennis-m-ritchie/kbman.pdf
https://www.nokia.com/bell-labs/about/dennis-m-ritchie/btut.html
https://www.nokia.com/bell-labs/about/dennis-m-ritchie/btut.pdf

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Re: Taming The Switch-Statement
#159
Author: bart
Date: Sun, 11 Oct 2026 00:43
43 lines
3295 bytes
On 10/10/2026 23:58, Michael S wrote:
> On Sat, 10 Oct 2026 15:32:32 -0700
> Keith Thompson <Keith.S.Thompson+u@gmail.com> wrote:
> 
>> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
>>> On 2026-10-10 22:03, Michael S wrote:
>>>> The cases where I want to break out of the loop from the switch in
>>>> the
>>>> body of the loop are very common.
>>>
>>> Ah, so you'd have needed something like Kornshell's 'break 2' to
>>> leave more than one level. - I suppose, you needed to used a 'goto'
>>> instead (and avoid the 'break' completely for those cases).
>>
>> Something like that, sure, but please not that.
>>
>> Specifying the *number* of levels to break or continue is IMHO
>> horrible.  "break N" makes me count things so the computer doesn't
>> have to.
>>
>> There are proposals, and precedents in other languages, for *named*
>> loops, and I'd like to see that in a future C.
>>
> 
> Yes. Break n is a maintanance nightmare.


I use numbered loops (in my syntaxes). At the same time, I don't, since 
breaking across nested versions is uncommon.

But when needed, then invariably it will be the outermost loop, which 
also has the loop index '0', which be written 'all'.


> Ada syntax (optional label before loop) is a lot better.
Actually it makes little difference, maintenance-wise.

Both absolute references to loops (labels) and relative references 
(indices) have complementary set of problems, when loops are added or 
inserted or removed.

But as I said the most common requirement IME is to break out of either 
the current loop, or the whole lot.
Re: Taming The Switch-Statement
#160
Author: Johann 'Myrkraverk' Oskarsson
Date: Sun, 11 Oct 2026 01:09
51 lines
4101 bytes
On 10/11/2026 6:58 AM, Lawrence D’Oliveiro wrote:
> On Sat, 10 Oct 2026 15:30:54 -0700, Andrey Tarasevich wrote:
> 
>> But `break` and `continue` behave differently inside `switch` in C:
>> the former can "see" the enveloping `switch` statements, while for
>> the latter all enveloping `switch` statements are completely
>> transparent. So, in order to refer to the same cycle one'd have to
>> use different nesting numbers in `break` and `continue` when used
>> inside `switch`(-es) in C. That would look quite confusing.
> 
> It also led to a major real-world calamity: the Great AT&T Telephone
> Crash of 15th January 1990. To quote from Bruce Sterling’s “The Hacker
> Crackdown”:
> 
>      As it happened, the problem itself -- the problem per se -- took
>      this form. A piece of telco software had been written in C
>      language, a standard language of the telco field. Within the C
>      software was a long "do... while" construct. The "do... while"
>      construct contained a "switch" statement. The "switch" statement
>      contained an "if" clause. The "if" clause contained a "break." The
>      "break" was *supposed* to "break" the "if clause." Instead, the
>      "break" broke the "switch" statement.
> 
> Back at the time, law enforcement was just cottoning on to the idea
> that evil people could use their technical skills with computers to
> wreak havoc with all kinds of crucial infrastructure. AT&T figured
> out, within nine hours, that the problem here was purely a mistake in
> their software, but it took somewhat longer for some authorities to be
> disabused of the notion that this was intentional sabotage.
> 
> <http://web.archive.org/web/20031204221934/www.chriswaltrip.com/sterling/>

I don't see this as a problem with C.  This can happen in any program-
ming language, and code with nested control structures.

And if I recall correctly, you can't use /break/ with a label inside a
switch in Java -- please correct me if I'm wrong, I'm feeling lazy to
check it out right now -- which results in similar shenanigans and po-
tentially even more convoluted control structures.

So, Lawrence, please enlighten us about how you concoct convoluted con-
trol structures in Python, because that's what you live for.



Best wishes, and happy convolution inside control structures in C!
-- 
Johann | email: invalid -> com | http://www.myrkraverk.com/blog/
I'm not from the Internet, I just work there. | via Easynews.com
https://bsky.app/profile/myrkraverk.bsky.social | for ( ;; ) _:;
Federated at https://fed.brid.gy/bsky/myrkraverk.bsky.social
Re: Taming The Switch-Statement
#161
Author: Johann 'Myrkraverk' Oskarsson
Date: Sun, 11 Oct 2026 01:12
43 lines
2954 bytes
On 10/11/2026 6:32 AM, Keith Thompson wrote:
> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
>> On 2026-10-10 22:03, Michael S wrote:
>>> The cases where I want to break out of the loop from the switch in
>>> the
>>> body of the loop are very common.
>>
>> Ah, so you'd have needed something like Kornshell's 'break 2' to leave
>> more than one level. - I suppose, you needed to used a 'goto' instead
>> (and avoid the 'break' completely for those cases).
> 
> Something like that, sure, but please not that.
> 
> Specifying the *number* of levels to break or continue is IMHO
> horrible.  "break N" makes me count things so the computer doesn't
> have to.
> 
> There are proposals, and precedents in other languages, for *named*
> loops, and I'd like to see that in a future C.
> 

What's wrong with labels?  We already have that.  You can name your
loops like this,

   foo: while ( bar ) {
     /* ... */
     for ( int i = 0 ; i < 10 ; i++ ) {
       /* ... */
       goto foo ;
     }
     /* ... */
   }

and do all kinds of control structures with just C89.  So, why would you
personally need named loops?  Can't you code C at all?


Best wishes, and happy named loops!
-- 
Johann | email: invalid -> com | http://www.myrkraverk.com/blog/
I'm not from the Internet, I just work there. | via Easynews.com
https://bsky.app/profile/myrkraverk.bsky.social | for ( ;; ) _:;
Federated at https://fed.brid.gy/bsky/myrkraverk.bsky.social
Re: Taming The Switch-Statement
#162
Author: bart
Date: Sun, 11 Oct 2026 01:12
79 lines
3968 bytes
On 11/10/2026 00:30, Keith Thompson wrote:
> bart <bc@freeuk.com> writes:

> Huh?  "computed goto" is not a looping construct.

You only hear about it in the context of interpreter dispatch loops.

>> (Of, course, my language has it all:
> 
> Of course it does.

Well, it does; what more can I say.
> 
> [...]
> 
>>> The ANSI C Rationale says "No serious consideration was given to
>>> making the switch more structured, as in Pascal, out of fear of
>>> invalidating working code".
>>>
>>> I suppose some version of C could have defined a new switch-like
>>> statement without the fallthrough behavior.  I can see some small
>>> advantages in doing so, but the existing switch with fallthrough
>>> would have to be kept in the language -- and such a new switch-like
>>> statement would have added no real expressive power.  We'd now have
>>> a mix of code using the old and new constructs, pressure to convert
>>> existing working code, and probably errors introduced by converting
>>> code incorrectly.
>>
>> I guess the same rationale means it is stuck with for(;;) loops?
> 
> Yes, of course it does.  Did you think that a construct that's used in
> most existing C programs could just be removed from the language?

I didn't say they should be removed.

>>     case 10: default: case 20:
> 
> Doctor, it hurts when I do this.

It illustrates having too much flexibility. Do compilers check for 
nonsense like this?

Having proper structure must make code analysis simpler than effectively 
having a bunch of case labels randomly scattered through the code.

Example:

    newswitch (expr)
    case 3, 4, 5:
       stmt1;
    case 6...10, 12:
       stmt2;
    else
       stmt3;

I think this is OK except for the possibility of that 'else' being 
attached to stmt2 when that ends with 'if (cond) stmt;'. But C already 
has a rule for that and existing means to get around it.

I haven't put in provision for fall-through. If people want that, then 
old switch will still work.

In this new statement, there is no special meaning for 'break'; it will 
be part of any enclosing old switch or loop.


>> It could also be easy to implement as structured switch can be
>> syntactic sugar for an if-else-if chain.
> 
> If you want an if-else-if chain, write an if-else-if chain.

Then why bother with switch at all?

An implementation HAS to support if-else, so I'm suggesting it wouldn't 
be hard to implement structured switch, since lowering to if-else is one 
easy option.


Re: Taming The Switch-Statement
#165
Author: Janis Papanagnou
Date: Sun, 11 Oct 2026 01:41
53 lines
3874 bytes
On 2026-10-11 00:54, Keith Thompson wrote:
> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
>> On 2026-10-10 18:50, Michael S wrote:
>>> I fully agree with your post (plus have to add that "more structured
>>> switch" apart from new keyword(s) will need some new way to express
>>> common handler for several cases. Ada/VHDL solution of using | would
>>> not work in C for obvious reasons).
>>
>> Pascal allows '..' and ',' (for ranges and lists), and even mixed.
>> That should (in principle) be a syntactical possibility in "C".
> 
> C2Y will add case ranges using "..." (which is already a token used for
> variadic functions), with syntax and semantics close to the existing gcc
> extension.
> 
>      switch (foo) {
>          case 'a' ... 'z':
>              // ...
>      }
> 
> This was considered and rejected (with "..") for C89.  One reason for
> rejecting it was that 'A'..'Z' is not contiguous in all character
> sets (particularly not in EBCDIC).  The C89 Rationale also mentions
> the problem of large code or jump table space for something like
> 0..65535, something that can be handled these days by minimally
> clever compilers.
> 
> One problem is that `case 0...1:` is a syntax error.  0...1 is a valid
> preprocessing number that can't be converted to a valid constant.
> The solution is to surround the ...  with spaces, which is probably
> a good idea anyway.
> 
> As for ',', that would avoid having to repeat the "case" keyword,
> but it could be visually confusing.  `case 0, 1:` is currently a
> syntax error, but only because a constant expression can't include
> a comma operator (with some obscure exceptions).  Allowing commas
> would prevent a future version of the language from either allowing
> comma operators in constant expressions or permitting non-constant
> expressions in case labels.  I still wouldn't mind such a change,
> but it would add no real expressive power and I don't think anyone
> has proposed it.

Thanks for the interesting background information.

Your explanation shows how difficult it is to add features (even if
they are comparably simple appearing ones) to an existing language;
many things have to be considered, interdependencies, and also an
educated thought about future consequences.

It's certainly a lot easier if you can design a language from scratch.

Janis
Re: Taming The Switch-Statement
#166
Author: Johann 'Myrkraverk' Oskarsson
Date: Sun, 11 Oct 2026 01:51
81 lines
4937 bytes
On 10/11/2026 9:41 AM, Janis Papanagnou wrote:
> On 2026-10-11 00:54, Keith Thompson wrote:
>> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
>>> On 2026-10-10 18:50, Michael S wrote:
>>>> I fully agree with your post (plus have to add that "more structured
>>>> switch" apart from new keyword(s) will need some new way to express
>>>> common handler for several cases. Ada/VHDL solution of using | would
>>>> not work in C for obvious reasons).
>>>
>>> Pascal allows '..' and ',' (for ranges and lists), and even mixed.
>>> That should (in principle) be a syntactical possibility in "C".
>>
>> C2Y will add case ranges using "..." (which is already a token used for
>> variadic functions), with syntax and semantics close to the existing gcc
>> extension.
>>
>>      switch (foo) {
>>          case 'a' ... 'z':
>>              // ...
>>      }
>>
>> This was considered and rejected (with "..") for C89.  One reason for
>> rejecting it was that 'A'..'Z' is not contiguous in all character
>> sets (particularly not in EBCDIC).  The C89 Rationale also mentions
>> the problem of large code or jump table space for something like
>> 0..65535, something that can be handled these days by minimally
>> clever compilers.
>>
>> One problem is that `case 0...1:` is a syntax error.  0...1 is a valid
>> preprocessing number that can't be converted to a valid constant.
>> The solution is to surround the ...  with spaces, which is probably
>> a good idea anyway.
>>
>> As for ',', that would avoid having to repeat the "case" keyword,
>> but it could be visually confusing.  `case 0, 1:` is currently a
>> syntax error, but only because a constant expression can't include
>> a comma operator (with some obscure exceptions).  Allowing commas
>> would prevent a future version of the language from either allowing
>> comma operators in constant expressions or permitting non-constant
>> expressions in case labels.  I still wouldn't mind such a change,
>> but it would add no real expressive power and I don't think anyone
>> has proposed it.
> 
> Thanks for the interesting background information.
> 
> Your explanation shows how difficult it is to add features (even if
> they are comparably simple appearing ones) to an existing language;
> many things have to be considered, interdependencies, and also an
> educated thought about future consequences.
> 
> It's certainly a lot easier if you can design a language from scratch.
> 
> Janis

Dear Javis,

Even then, people screw up, such as Java's lack of labelled /break/s in-
side switch () statements.  I guess they were afraid of /goto/s, and
chose to use /break/ instead, with this annoying side effect.

[Ok, I'll probably want to review that before I post more about it, but
I have faith in my recollection.]

C++ has removed some features from C++98, and again from C++11 if I re-
call correctly, so it's not like people don't screw up from time to
time.

I've not used C# extensively enough to encounter problem spots, so
people here in comp.lang.c are welcome to chime in.

My personal guess is that it would be better for everyone, if program-
ming languages didn't escape the laboratory until at least one more non-
trivial project other than the compiler is near completion or finished.


What do you think?
-- 
Johann | email: invalid -> com | http://www.myrkraverk.com/blog/
I'm not from the Internet, I just work there. | via Easynews.com
https://bsky.app/profile/myrkraverk.bsky.social | for ( ;; ) _:;
Federated at https://fed.brid.gy/bsky/myrkraverk.bsky.social
Re: Taming The Switch-Statement
#167
Author: Janis Papanagnou
Date: Sun, 11 Oct 2026 01:58
35 lines
3427 bytes
On 2026-10-11 00:30, Andrey Tarasevich wrote:
> On Sat 10/10/2026 1:33 PM, Janis Papanagnou wrote:
>> On 2026-10-10 22:03, Michael S wrote:
>>>
>>> The cases where I want to break out of the loop from the switch in the
>>> body of the loop are very common.
>>
>> Ah, so you'd have needed something like Kornshell's 'break 2' to leave
>> more than one level.
>
> Yes, but that would be rather inelegant in the overall scheme of things 
> in C, since once we start talking about `break 2` it would be logical to 
> consider `continue 2` as well (i.e. like Kornshell's `continue`).
> 
> But `break` and `continue` behave differently inside `switch` in C: the 
> former can "see" the enveloping `switch` statements, while for the 
> latter all enveloping `switch` statements are completely transparent. 
> So, in order to refer to the same cycle one'd have to use different 
> nesting numbers in `break` and `continue` when used inside `switch`(-es) 
> in C. That would look quite confusing.

Personally I don't like jumps in programming at all, but sometimes a
break is clearer than embedding a boolean into a surrounding control
structure and keeping explicitly track of the exit state value. Even
less I like a 'goto'; the one case where I find it worthwhile, to jump
from within nested loops to the continuation point after the nested
loops, is not something I like, but I also only very rarely needed it
and I wouldn't mind using it. Similar with the 'break N' and 'continue
N' in Kornshell; I would be surprised if I had used it more than once
or at most twice in decades. - I'm generally using what the languages
provide and what is best maintainable. - As I see it there's no single
perfect way how to address that issue. YMMV.

Janis
Re: Taming The Switch-Statement
#169
Author: Janis Papanagnou
Date: Sun, 11 Oct 2026 02:07
39 lines
3190 bytes
On 2026-10-11 00:32, Keith Thompson wrote:
> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
>> On 2026-10-10 22:03, Michael S wrote:
>>> The cases where I want to break out of the loop from the switch in
>>> the
>>> body of the loop are very common.
>>
>> Ah, so you'd have needed something like Kornshell's 'break 2' to leave
>> more than one level. - I suppose, you needed to used a 'goto' instead
>> (and avoid the 'break' completely for those cases).
> 
> Something like that, sure, but please not that.
> 
> Specifying the *number* of levels to break or continue is IMHO
> horrible.  "break N" makes me count things so the computer doesn't
> have to.

I agree; that's what I also dislike about it.

The point is the question what choices you have. The 'goto' is IMO
the worst; because of semantic interdependencies that will regularly
lead to semantical restrictions about its applicability (or placement
of labels); various languages have various restrictions, it's just
a mess! The 'break' is a "cheap" solution, but also very restricted.
There's yet other variants with their own drawbacks; I won't even
start with it.

> 
> There are proposals, and precedents in other languages, for *named*
> loops, and I'd like to see that in a future C.

One of the better possibilities, maybe; but still not satisfying for
my (very subjective) taste.

(Some language let you organize such things in completely other ways
with no need for jumps of any sort.)

Janis
Re: Taming The Switch-Statement
#170
Author: Keith Thompson
Date: Sun, 11 Oct 2026 02:55
113 lines
6073 bytes
bart <bc@freeuk.com> writes:
> On 11/10/2026 00:30, Keith Thompson wrote:
>> bart <bc@freeuk.com> writes:
>
>> Huh?  "computed goto" is not a looping construct.
>
> You only hear about it in the context of interpreter dispatch loops.

I hardly hear about it at all.  I'm aware that it exists as a gcc
extension.  I don't think I've ever used it.  I see no point in
discussing it further.

>> [...]
>> 
>>>> The ANSI C Rationale says "No serious consideration was given to
>>>> making the switch more structured, as in Pascal, out of fear of
>>>> invalidating working code".
>>>>
>>>> I suppose some version of C could have defined a new switch-like
>>>> statement without the fallthrough behavior.  I can see some small
>>>> advantages in doing so, but the existing switch with fallthrough
>>>> would have to be kept in the language -- and such a new switch-like
>>>> statement would have added no real expressive power.  We'd now have
>>>> a mix of code using the old and new constructs, pressure to convert
>>>> existing working code, and probably errors introduced by converting
>>>> code incorrectly.
>>>
>>> I guess the same rationale means it is stuck with for(;;) loops?
>>
>> Yes, of course it does.  Did you think that a construct that's used
>> in most existing C programs could just be removed from the language?
>
> I didn't say they should be removed.

So you want to add a new and less flexible looping construct on top
of the existing one, making the language more complicated with no
real additional expressive power.  (C++'s for loops are a different
matter, sensible because iterators are such a big part of the C++
standard library.)

>>>     case 10: default: case 20:
>>
>> Doctor, it hurts when I do this.
>
> It illustrates having too much flexibility. Do compilers check for
> nonsense like this?

I fundamentally disagree with your claim of "too much flexibility".

"case 10: default: case 20:" perfectly valid, syntactically and
semantically.  It's also silly, and not something someone would
plausibly write other than to make a point.  I see no reason for
compilers to go out of their way to do anything about it.  It's
reasonable for a compiler to warn about plausible errors.  Putting
"default:" in the middle of a set of cases isn't a plausible
error, and I'm fine with the compiler not wasting its time with a
special warning.  (I'd also be fine with a compiler warning about it.)

> Having proper structure must make code analysis simpler than
> effectively having a bunch of case labels randomly scattered through
> the code.

Not really.  A reasonably clever compiler or other tool can easily
recognize a typical switch statement where each sequence of case or
default labels is followed by a "break".  Code analysis becomes a little
more difficult when that pattern is broken by any of several means:
fallthrough, goto, return, continue.

> Example:
[snip]

[...]

>>> It could also be easy to implement as structured switch can be
>>> syntactic sugar for an if-else-if chain.
>>
>> If you want an if-else-if chain, write an if-else-if chain.
>
> Then why bother with switch at all?

It expresses a common pattern.  It can, especially with older compilers,
result in more efficient code (a jump table) that an if/else chain
cannot directly express.  It lets the expression be written and
evaluated just once.  It makes the compiler diagnose the error of
specifying the same value more than once.  It is as expressive as the
more restrictive case statement seen in Pascal and other languages.

It's what we have in the language.  Nobody suggests that it's ideal
or perfect.

Or we could drop every control structure other than "if" and "goto".

> An implementation HAS to support if-else, so I'm suggesting it
> wouldn't be hard to implement structured switch, since lowering to
> if-else is one easy option.

How would your "structured switch" differ from the current switch
statement?  Would the lack of fallthrough be the only difference?
Would the case expressions still have to be constant?  Would you
allow duplicate values?  Would you allow non-integer types, perhaps
with user-defined comparisons?  These are all rhetorical questions,
intended merely to point out that this is not as simple as you seem
to think it is.

Would it add *any* real expressive power to a language that you
hold in contempt anyway?

Sure, we could add every feature that's not too hard to implement.
The end result would be a huge mess.

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Re: Taming The Switch-Statement
#171
Author: Keith Thompson
Date: Sun, 11 Oct 2026 03:13
56 lines
4236 bytes
Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
> On 2026-10-11 00:32, Keith Thompson wrote:
>> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
>>> On 2026-10-10 22:03, Michael S wrote:
>>>> The cases where I want to break out of the loop from the switch in
>>>> the
>>>> body of the loop are very common.
>>>
>>> Ah, so you'd have needed something like Kornshell's 'break 2' to leave
>>> more than one level. - I suppose, you needed to used a 'goto' instead
>>> (and avoid the 'break' completely for those cases).
>> Something like that, sure, but please not that.
>> Specifying the *number* of levels to break or continue is IMHO
>> horrible.  "break N" makes me count things so the computer doesn't
>> have to.
>
> I agree; that's what I also dislike about it.
>
> The point is the question what choices you have. The 'goto' is IMO
> the worst; because of semantic interdependencies that will regularly
> lead to semantical restrictions about its applicability (or placement
> of labels); various languages have various restrictions, it's just
> a mess! The 'break' is a "cheap" solution, but also very restricted.
> There's yet other variants with their own drawbacks; I won't even
> start with it.
>
>> There are proposals, and precedents in other languages, for *named*
>> loops, and I'd like to see that in a future C.
>
> One of the better possibilities, maybe; but still not satisfying for
> my (very subjective) taste.
>
> (Some language let you organize such things in completely other ways
> with no need for jumps of any sort.)

I find "break NAME;", where "NAME" is the name of an enclosing
construct, unambiguously better than "break N;", where N is the
number of levels to break out of.

The "break N" syntax is specified by POSIX.  It's supported by ksh,
bash, dash, zsh, and probably other Bourne-based shells.  (My guess
is that it originated in ksh.)  My best guess is that because the
Bourne-like shells don't have gotos, they don't have labels, so
named loops would have required inventing those too.  And admittedly
I suppose it's not too bad if it's no more than a couple of levels --
but it's still easy to, ahem, *break* if you reorganize the code.

There's a proposal for C2y to use goto labels as loop names, and a
competing one to define a new syntax like "for NAME (;;)" :

https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3355.htm
https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3377.pdf

-- 
Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.com
void Void(void) { Void(); } /* The recursive call of the void */
Re: Taming The Switch-Statement
#173
Author: Waldek Hebisch
Date: Sun, 11 Oct 2026 05:52
60 lines
4130 bytes
David Brown <david.brown@hesbynett.no> wrote:
> On 10/10/2026 15:11, bart wrote:
>> On 10/10/2026 13:01, Janis Papanagnou wrote:
>>> On 2026-10-10 12:53, bart wrote:
>>>> On 10/10/2026 03:17, Keith Thompson wrote:
>>> [...]
>> 
>>> I think the problem with your statement is also that you think your
>>> preferred construct is the only one that is "right". (You seem to
>>> be confident that supporting "fall-though" is generally "wrong".)
>> 
>> Yes. Why, you think that fall-through is right AND should be the default 
>> behaviour?
>> 
>> If you look at actual C codebases, fall-through is incredibly rare. 
>> Nearly always, it will use break, or sometimes other control-flow such 
>> as return or goto, so that fall-through doesn't happen.
>> 
> Keith explained the background for C's switch.  It has its origins in a 
> time when "goto" was commonly used, and it is a significant improvement 
> on many uses of calculated goto.  It is not "bizarre", dangerous, or 
> "dumb" - or "wrong".  It is simple /different/ from the structured 
> switch/case/match construct found in many other languages.  The choice 
> was made long ago, and it must be obvious to everyone that the behaviour 
> could not be changed.
> 
> This makes it flexible - you can do things with C's "switch" that you 
> cannot do with Pascal "case".  That means you can do some different, 
> interesting and useful things - and it also means you can make some 
> different and annoying mistakes.

AFAICS Pascal-style 'case' + 'goto' that can jump inside constructs
can do everthing C 'switch' can do.  Falltrough is just jump to
another case, disallowed in Pascal, but legal in C.  Similarly,
other unstructured uses of 'switch' could be done using combination
of structured 'switch' and 'goto'.  Structured uses are much more
frequent, so really there is no argument for C-style 'switch' except
for backward compatibility (which is deciding argument).

> 2. C programmers would mostly also have been fine with a structured 
> "switch" where each "case" had its own block and there was no 
> fall-through.  There are, however, occasional exceptions and more 
> complicated code.  Such use-cases would need to be handled in other ways 
> if C's switch did not work as it does.  My gut feeling is that a solid 
> proportion of such cases were more relevant in the old days before more 
> optimising compilers - things like Duff's Device spring to mind as being 
> useful long ago, but unnecessary with modern tools.

Using 'goto' + structured 'switch' one needs only two optimizations to
get the same code as from C 'switch':

1) 'goto' to instruction directly following it should be deleted,
2) if body of a case consists of single 'goto' for this case
   'switch' should transfer control to the target of 'goto'.

Those are very simple optimizations and could be included in
rather small compiler (like one running on PDP-11).

-- 
                              Waldek Hebisch
Re: Taming The Switch-Statement
#185
Author: Waldek Hebisch
Date: Sun, 11 Oct 2026 08:00
41 lines
3393 bytes
Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
> On 2026-10-10 22:09, bart wrote:
>> On 10/10/2026 19:08, Janis Papanagnou wrote:
>>> [*] In the GNU version of Awk - a much simpler but higher abstracted
>>> language - you can nicely compare strings, and even regexps.
>> 
>> I have a narrow view of SWITCH, which is specifically for use with 
>> integer values. That allows comparison of N unique possibilities 
>> simultaneously, or in O(1) time.
>> So if you're comparing strings, then it is not SWITCH IMO, unless those 
>> strings are perhaps interned.
> 
> A CDC 175/176 carried a Pascal TEXT object in one machine word and
> could compare it as atom. Newer standard PC CPUs have more bits in
> a word than those former supercomputers. - But the point here was
> that internals should be abstracted by a higher level programming
> language. - And compilers have principally various possibilities to
> support some "atomization" of string comparisons with compile-time
> string constants. - As said, it would have been useful in many of
> my application cases. (No more, no less.)

In C there are multi-character "characters".  Details are implementation
defined, but AFAICS on 64-bit machine you can pack 8 bytes into single
machine word and use that in a switch.  CDC used 6 bit characters, so
it could cram 10 characters into a single word.  Corresponding comparison
of strings would execute as a single machine instruction.  But AFAIK
Pascal did not allow to use strings in 'case' statement.

In principle C compiler could generate matching code for strings,
basically if all cases correspond to short strings it could pack
characters into a single machine word and then reuse integer
case.  For longer strings it could generate either tree of
comparisons (IIUC some sparse switches use this) or use hashing
to find correct case.  That would be modest extention of current
switch (with sparse case labels one needs to handle most of it
anyway).  I would guess that main counterargument to such a switch
is C++ compatibility: clearly C++ would want such things for classes
and it opens a can of worms.

-- 
                              Waldek Hebisch
Re: Taming The Switch-Statement
#186
Author: Janis Papanagnou
Date: Sun, 11 Oct 2026 08:27
59 lines
4614 bytes
On 2026-10-11 10:00, Waldek Hebisch wrote:
> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
>> On 2026-10-10 22:09, bart wrote:
>>> On 10/10/2026 19:08, Janis Papanagnou wrote:
>>>> [*] In the GNU version of Awk - a much simpler but higher abstracted
>>>> language - you can nicely compare strings, and even regexps.
>>>
>>> I have a narrow view of SWITCH, which is specifically for use with
>>> integer values. That allows comparison of N unique possibilities
>>> simultaneously, or in O(1) time.
>>> So if you're comparing strings, then it is not SWITCH IMO, unless those
>>> strings are perhaps interned.
>>
>> A CDC 175/176 carried a Pascal TEXT object in one machine word and
>> could compare it as atom. Newer standard PC CPUs have more bits in
>> a word than those former supercomputers. - But the point here was
>> that internals should be abstracted by a higher level programming
>> language. - And compilers have principally various possibilities to
>> support some "atomization" of string comparisons with compile-time
>> string constants. - As said, it would have been useful in many of
>> my application cases. (No more, no less.)
> 
> In C there are multi-character "characters".  Details are implementation
> defined, but AFAICS on 64-bit machine you can pack 8 bytes into single
> machine word and use that in a switch.  CDC used 6 bit characters, so
> it could cram 10 characters into a single word.  Corresponding comparison
> of strings would execute as a single machine instruction.  But AFAIK
> Pascal did not allow to use strings in 'case' statement.

That is absolutely correct; about the PACKED ARRAY [1..10] OF CHAR
on these CDCs, and about what the Pascal language's CASE allowed
per language definition, which was any enumerable type, and strings
were, being arrays, not enumerable.

I seem to recall that operations on the Pascal's TEXT type were not
very elaborated, though. And assignments were possible for any type
not restricted to primitive types or the TEXT type.

My point was, as you also wrote, that there's possibilities to handle
a short string at least as an atom for comparisons in principle (if
the language definition allows that, if it's appropriately defined).

> 
> In principle C compiler could generate matching code for strings,
> basically if all cases correspond to short strings it could pack
> characters into a single machine word and then reuse integer
> case.  For longer strings it could generate either tree of
> comparisons (IIUC some sparse switches use this) or use hashing
> to find correct case.  That would be modest extention of current
> switch (with sparse case labels one needs to handle most of it
> anyway).  I would guess that main counterargument to such a switch
> is C++ compatibility: clearly C++ would want such things for classes
> and it opens a can of worms.

Yes, probably. - There's so many things you cannot do now, decades
after the base of "C" has been defined.

Janis
Re: Taming The Switch-Statement
#187
Author: Janis Papanagnou
Date: Sun, 11 Oct 2026 08:36
30 lines
2978 bytes
On 2026-10-11 05:13, Keith Thompson wrote:
> 
> I find "break NAME;", where "NAME" is the name of an enclosing
> construct, unambiguously better than "break N;", where N is the
> number of levels to break out of.

Yes, sure.

(Reminds me Pascal that supported for 'goto' just integer numbers
[in the range 1..9999, IIRC] for jumps. - This is different from
'break N' but still also a bad design, IMO. - Not sure about later
Pascal dialects, though. - Numbers for labels or levels, not nice.)

> 
> The "break N" syntax is specified by POSIX.  It's supported by ksh,
> bash, dash, zsh, and probably other Bourne-based shells.  (My guess
> is that it originated in ksh.)  My best guess is that because the
> Bourne-like shells don't have gotos, they don't have labels, so
> named loops would have required inventing those too.  And admittedly
> I suppose it's not too bad if it's no more than a couple of levels --
> but it's still easy to, ahem, *break* if you reorganize the code.

Yes. - But while I don't find it (the N) elegant as concept it's
in practice not that bad WRT "reorganization of code" since it's
(as opposed to the 'goto' in other languages) a local construct.

Janis

> [...]
Re: Taming The Switch-Statement
#189
Author: Janis Papanagnou
Date: Sun, 11 Oct 2026 08:49
68 lines
5098 bytes
On 2026-10-11 10:27, Janis Papanagnou wrote:
> On 2026-10-11 10:00, Waldek Hebisch wrote:
>> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
>>> On 2026-10-10 22:09, bart wrote:
>>>> On 10/10/2026 19:08, Janis Papanagnou wrote:
>>>>> [*] In the GNU version of Awk - a much simpler but higher abstracted
>>>>> language - you can nicely compare strings, and even regexps.
>>>>
>>>> I have a narrow view of SWITCH, which is specifically for use with
>>>> integer values. That allows comparison of N unique possibilities
>>>> simultaneously, or in O(1) time.
>>>> So if you're comparing strings, then it is not SWITCH IMO, unless those
>>>> strings are perhaps interned.
>>>
>>> A CDC 175/176 carried a Pascal TEXT object in one machine word and
>>> could compare it as atom. Newer standard PC CPUs have more bits in
>>> a word than those former supercomputers. - But the point here was
>>> that internals should be abstracted by a higher level programming
>>> language. - And compilers have principally various possibilities to
>>> support some "atomization" of string comparisons with compile-time
>>> string constants. - As said, it would have been useful in many of
>>> my application cases. (No more, no less.)
>>
>> In C there are multi-character "characters".  Details are implementation
>> defined, but AFAICS on 64-bit machine you can pack 8 bytes into single
>> machine word and use that in a switch.  CDC used 6 bit characters, so
>> it could cram 10 characters into a single word.  Corresponding comparison
>> of strings would execute as a single machine instruction.  But AFAIK
>> Pascal did not allow to use strings in 'case' statement.
> 
> That is absolutely correct; about the PACKED ARRAY [1..10] OF CHAR
> on these CDCs, and about what the Pascal language's CASE allowed
> per language definition, which was any enumerable type, and strings
> were, being arrays, not enumerable.

I just looked it up in an old book; you could (in Pascal) also
compare "strings" (PACKED ARRAY OF TEXT) by the six comparison
operators (where other general array type objects needed an
element-wise comparison). So you could at least compare strings
of type TEXT directly with IF (and need no function, as in "C").

> 
> I seem to recall that operations on the Pascal's TEXT type were not
> very elaborated, though. And assignments were possible for any type
> not restricted to primitive types or the TEXT type.
> 
> My point was, as you also wrote, that there's possibilities to handle
> a short string at least as an atom for comparisons in principle (if
> the language definition allows that, if it's appropriately defined).
> 
>>
>> In principle C compiler could generate matching code for strings,
>> basically if all cases correspond to short strings it could pack
>> characters into a single machine word and then reuse integer
>> case.  For longer strings it could generate either tree of
>> comparisons (IIUC some sparse switches use this) or use hashing
>> to find correct case.  That would be modest extention of current
>> switch (with sparse case labels one needs to handle most of it
>> anyway).  I would guess that main counterargument to such a switch
>> is C++ compatibility: clearly C++ would want such things for classes
>> and it opens a can of worms.
> 
> Yes, probably. - There's so many things you cannot do now, decades
> after the base of "C" has been defined.
> 
> Janis
> 
Re: Taming The Switch-Statement
#192
Author: Janis Papanagnou
Date: Sun, 11 Oct 2026 09:00
14 lines
1796 bytes
On 2026-10-11 04:55, Keith Thompson wrote:
> bart <bc@freeuk.com> writes:
>> [...]
> 
> Or we could drop every control structure other than "if" and "goto".

Even 'goto' is redundant if we program in a functional programming way.

*evil grin* ;-)

Janis

> [...]
Re: Taming The Switch-Statement
#197
Author: David Brown
Date: Sun, 11 Oct 2026 09:41
69 lines
4861 bytes
On 11/10/2026 03:41, Janis Papanagnou wrote:
> On 2026-10-11 00:54, Keith Thompson wrote:
>> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
>>> On 2026-10-10 18:50, Michael S wrote:
>>>> I fully agree with your post (plus have to add that "more structured
>>>> switch" apart from new keyword(s) will need some new way to express
>>>> common handler for several cases. Ada/VHDL solution of using | would
>>>> not work in C for obvious reasons).
>>>
>>> Pascal allows '..' and ',' (for ranges and lists), and even mixed.
>>> That should (in principle) be a syntactical possibility in "C".
>>
>> C2Y will add case ranges using "..." (which is already a token used for
>> variadic functions), with syntax and semantics close to the existing gcc
>> extension.
>>
>>      switch (foo) {
>>          case 'a' ... 'z':
>>              // ...
>>      }
>>
>> This was considered and rejected (with "..") for C89.  One reason for
>> rejecting it was that 'A'..'Z' is not contiguous in all character
>> sets (particularly not in EBCDIC).  The C89 Rationale also mentions
>> the problem of large code or jump table space for something like
>> 0..65535, something that can be handled these days by minimally
>> clever compilers.
>>
>> One problem is that `case 0...1:` is a syntax error.  0...1 is a valid
>> preprocessing number that can't be converted to a valid constant.
>> The solution is to surround the ...  with spaces, which is probably
>> a good idea anyway.
>>
>> As for ',', that would avoid having to repeat the "case" keyword,
>> but it could be visually confusing.  `case 0, 1:` is currently a
>> syntax error, but only because a constant expression can't include
>> a comma operator (with some obscure exceptions).  Allowing commas
>> would prevent a future version of the language from either allowing
>> comma operators in constant expressions or permitting non-constant
>> expressions in case labels.  I still wouldn't mind such a change,
>> but it would add no real expressive power and I don't think anyone
>> has proposed it.
> 
> Thanks for the interesting background information.
> 
> Your explanation shows how difficult it is to add features (even if
> they are comparably simple appearing ones) to an existing language;
> many things have to be considered, interdependencies, and also an
> educated thought about future consequences.
> 

The comma operator turns up often as a hinder to syntax extension in 
C-like languages - disproportional, I think, to its usage in "typical" C 
code.  As a clear example, C++ had to deprecate its usage in subscript 
operators so that they could later support a multi-dimensional subscript 
operator.  "m[x, y]" meant "evaluate x, throw away the result, then 
evaluate m.operator[](y)" instead of the more useful "m.operator[](x, y)".

Still, C has the comma operator, some people like it, some code uses it, 
and it is not going anywhere.  And it would be nice if C can continue to 
avoid C++ style special exception rules.

> It's certainly a lot easier if you can design a language from scratch.
> 

Yes.  Or if you can, like Bart, just change your language to suit, or 
put in whatever inconsistencies and ambiguities you like because you 
know exactly how programmers will use the language.
Re: Taming The Switch-Statement
#199
Author: Stefan Ram
Date: Sun, 11 Oct 2026 10:14
24 lines
2576 bytes
Johann 'Myrkraverk' Oskarsson <johann@myrkraverk.invalid> wrote or quoted:
>I don't see this as a problem with C.  This can happen in any program-
>ming language, and code with nested control structures.

  I agree. Assuming a "break" will leave an "if" in C is an error
  of someone who has not learned C yet and who also did not bother
  to look up what he does not know or test his code. And it can
  perfectly be reproduced in other languages such as Python:

  main.py

while True:
    if True:
        break # leave the "if"
    print( "Success: If was left." )
print( "Failure: While was left." )    

  output

Failure: While was left.

  .

Page 1 of 9 • 412 total messages
Thread Navigation

This is a paginated view of messages in the thread with full content displayed inline.

Messages are displayed in chronological order, with the original post highlighted in green.

Use pagination controls to navigate through all messages in large threads.

Back to All Threads