🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

412 total messages Page 2 of 9 Started by Lawrence D’Oliveiro Sat, 10 Oct 2026 00:25
Page 2 of 9 • 412 total messages
Re: Taming The Switch-Statement
#206
Author: bart
Date: Sun, 11 Oct 2026 10:58
181 lines
8023 bytes
On 10/10/2026 16:50, David Brown 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.
> 
> 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.

We don't know that, we just see the end result.

The best one say about C-switch is that it can emulate a real switch 
statement. But when reading unfamiliar code, you can't be as confident 
as to the author's intentions: is that an ordinary switch, or is there 
something odd about it?

A bit like looking at a 'busy' for-statement header and trying to 
determine, is this a simple iteration, or is there something else going on?

Because unfortunately C's flexibility makes weird stuff possible.

C's 'switch' is truly bizarre. Below is an experiment where I took an 
ordinary function body, and wrapped 'switch' around it with randomly 
placed case labels.

It still worked (as I placed 'default:' near the start, and providing 
'm' is greater than 7), but What The Hell?

gcc with warnings says nothing useful about it.


>  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.

This is the core C code for Duff's Device from Wikipedia:

     switch (count % 8) {
         case 0: *to = *from++;
         case 7: *to = *from++;
         case 6: *to = *from++;
         case 5: *to = *from++;
         case 4: *to = *from++;
         case 3: *to = *from++;
         case 2: *to = *from++;
         case 1: *to = *from++;
     }

This is the emulation of it in my language ('to' is a reserved word, and 
that constuct is 1-based):

     goto (count rem 8| L1, L2, L3, L4, L5, L6, L7 | L0)

     L0: d^ := s++^
     L7: d^ := s++^
     L6: d^ := s++^
     L5: d^ := s++^
     L4: d^ := s++^
     L3: d^ := s++^
     L2: d^ := s++^
     L1: d^ := s++^

Those labels need to be unique, but probably you won't need more than 
one Duff's Device in any one function.

This could be done in C too via existing extensions.


> 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.

That is astounding. But then, how many other languages, which have 
copied all sorts of dubious features from C, have also duplicated its 
bizarre switch statement?

That should tell you more.

> 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,

I suggest you try the same exercise I did.

  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. 

I posted a proposal for such a statement in a reply to Keith Thompson, 
who completely dismissed it.

The fall-through feature is a minor detail.

-----------------------

static void nsieve(int m) {
     unsigned int count = 0, i, j;
     boolean * flags = (boolean *) malloc(m * sizeof(boolean));
     for (i = 0; i < m; ++i) flags[i]=1;

     for (i = 2; i < m; ++i)
         if (flags[i]) {
             ++count;
             for (j = i << 1; j < m; j += i)
                    flags[j] = 0;
     }

     free(flags);
     printf("Primes up to %8u %8u\n", m, count);
}

static void nsieve_sw(int m) {
     switch (m) {
     default:
     case 1:
         unsigned int count = 0, i, j;
     case 2:
         boolean * flags = (boolean *) malloc(m * sizeof(boolean));
         for (i = 0; i < m; ++i)
             case 3:
                 flags[i]=1;

         for (i = 2; i < m; ++i)
             if (flags[i]) {
             case 4:
                 ++count;
             case 5:
                 for (j = i << 1; j < m; j += i)
             case 6:
                        flags[j] = 0;
         }

         free(flags);
             case 7:
         printf("Primes up to %8u %8u\n", m, count);
     }
}
Re: Taming The Switch-Statement
#209
Author: bart
Date: Sun, 11 Oct 2026 11:21
137 lines
6270 bytes
On 11/10/2026 03:55, Keith Thompson wrote:
> 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.

>>> 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,

So how would you do it: remove existing switch completely and replace 
with the new version?

Obviously new and old will have to co-exist. This could have been done 
decades ago and the old switch deprecated by now.

> making the language more complicated with no
> real additional expressive power.

It's already getting more complicated.

>> It illustrates having too much flexibility. Do compilers check for
>> nonsense like this?
> 
> I fundamentally disagree with your claim of "too much flexibility".

So what more flexibility do you think switch could have: working across 
functions?
> "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 is nonsense, akin to writing this:

   if (cond) {
      s1;
      else
      s2;
   }

where the else branch is in the middle of the true branch. Is it 
possible that people truly don't realise how utterly bizarre C switch is?

Or if they do, it is astounding that they just shrug it off.


> 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.

See the example in my last post replying to David Brown. What 
control-flow analysis would a compiler make of that?


>> Example:
> [snip]

I see you're not very receptive of it.

> 
> [...]
> 
>>>> 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.

A common pattern where one of N blocks of code is executed according to 
some control expression.

But that's not what C switch does: it jumps to one of N random labels 
anywhere inside any statement of any complexity and depth.

Those N blocks can overlap. Or after executing one block, it just 
carries on into the next unless stopped via 'break'.

Often one of these N will be an exception (default) but in C that can be 
shared with of the other blocks.

Is this the common pattern you're talking about; total chaos?


> 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 an emulation of it but with few guardrails.

> 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.

Yes it is simple:

* The control expression is an integer
* Case values are constants, and must be unique
* The only comparison is a nominal ==

But it implements that common pattern properly as explained above.

The fall-through question doesn't arise, any more than it does in if-else.

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

It provides more safety and more confidence that no weird stuff is going 
on, and confidence that it is properly implementing the common pattern.


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

Then it would be right at home! This is fixing something that should 
long ago have been taken out and shot.
Re: Taming The Switch-Statement
#210
Author: Tim Rentsch
Date: Sun, 11 Oct 2026 11:26
7 lines
1772 bytes
Michael S <already5chosen@yahoo.com> writes:

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

That surprises me.  Can you post a representative example (and
ideally not overly long)?
Re: Taming The Switch-Statement
#211
Author: bart
Date: Sun, 11 Oct 2026 12:35
28 lines
2416 bytes
On 11/10/2026 12:26, Tim Rentsch wrote:
> Michael S <already5chosen@yahoo.com> writes:
> 
>> The cases where I want to break out of the loop from the switch in
>> the body of the loop are very common.
> 
> That surprises me.  Can you post a representative example (and
> ideally not overly long)?


An example shouldn't be necessary. It is enough to know that loop-breaks 
exist and are used.

Then, whether break works here:

    while (cond) {
         ....
         break;
         ....
    }

shouldn't need to depend on whether that break happens to be inside a 
switch statement.

Maybe it is within an if-else chain, but at some point it is refactored 
into a switch statement. Now it no long does what is expected, and in 
fact using break to quit the loop from inside switch becomes impossible.
Re: Taming The Switch-Statement
#212
Author: David Brown
Date: Sun, 11 Oct 2026 12:42
120 lines
7068 bytes
On 11/10/2026 12:58, bart wrote:
> On 10/10/2026 16:50, David Brown 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.
>>
>> 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.
> 
> We don't know that, we just see the end result.

I don't think there is anything much you can say about that without 
sidetracking to a definition of what we mean by "a problem", and then 
doing a massive survey of lots of C programmers.

We do know that C is a massively successful programming language, used 
by vast numbers of people, and that switch statements are common in C. 
This is true regardless of any real or imagined "problem" with C's 
switch statements.

> 
>>   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.
> 
> This is the core C code for Duff's Device from Wikipedia:
> 

We know what Duff's Device is, and no one cares about your language.  It 
is not an alternative to C in any way.

>> 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.
> 
> That is astounding. But then, how many other languages, which have 
> copied all sorts of dubious features from C, have also duplicated its 
> bizarre switch statement?
> 
> That should tell you more.

We could pick a dozen different real-world languages, with a dozen 
different kinds of switch, case, match or other multiple choice 
construct (or lack thereof).  That should tell you that there is no 
"right" or "wrong" choice here - there are different design choices, 
with different pros and cons, different flexibilities and limitations, 
and appropriate for different kinds of language and different kinds of 
tools.

> 
>> 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,
> 
> I suggest you try the same exercise I did.

I suggest you find something better to spend your time on than re-hashes 
of your obsessions about what you don't like about C.

> 
>   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. 
> 
> I posted a proposal for such a statement in a reply to Keith Thompson, 
> who completely dismissed it.
> 

Keith is a big boy, and responsible for his own opinions and posts - it 
is not my place to defend his writing.  However, I entirely agree with 
him in that post.  It would be possible to add a more structured 
switch-like statement to C, without fall-through, but doing so would be 
detrimental to the language as a whole as the disadvantages and added 
complexity would not be balanced by significant added usability or let 
you write code in a significantly better way.
Re: Taming The Switch-Statement
#213
Author: Tim Rentsch
Date: Sun, 11 Oct 2026 13:13
22 lines
2353 bytes
bart <bc@freeuk.com> writes:

> On 11/10/2026 12:26, Tim Rentsch wrote:
>
>> Michael S <already5chosen@yahoo.com> writes:
>>
>>> The cases where I want to break out of the loop from the switch in
>>> the body of the loop are very common.
>>
>> That surprises me.  Can you post a representative example (and
>> ideally not overly long)?
>
> An example shouldn't be necessary.  It is enough to know that
> loop-breaks exist and are used.

It doesn't surprise me that they exist.  What surprises me is
that they are common, in code written by someone I consider a
competent programmer.  I don't care about what idiotic things
are done by people who aren't competent programmers.

You might want to think about the deeper meaning of that last
sentence.
Re: Taming The Switch-Statement
#214
Author: David Brown
Date: Sun, 11 Oct 2026 13:33
44 lines
3384 bytes
On 11/10/2026 14:35, bart wrote:
> On 11/10/2026 12:26, Tim Rentsch wrote:
>> Michael S <already5chosen@yahoo.com> writes:
>>
>>> The cases where I want to break out of the loop from the switch in
>>> the body of the loop are very common.
>>
>> That surprises me.  Can you post a representative example (and
>> ideally not overly long)?
> 
> 
> An example shouldn't be necessary. It is enough to know that loop-breaks 
> exist and are used.
> 
> Then, whether break works here:
> 
>     while (cond) {
>          ....
>          break;
>          ....
>     }
> 
> shouldn't need to depend on whether that break happens to be inside a 
> switch statement.
> 
> Maybe it is within an if-else chain, but at some point it is refactored 
> into a switch statement. Now it no long does what is expected, and in 
> fact using break to quit the loop from inside switch becomes impossible.
> 

The question was not about how it is possible to write a loop within a 
switch and have a "break" statement inside the loop.  The question was 
about how often such code was written, and what makes it "very common" 
for Michael.  I am also curious to know if he finds the use of the same 
"break" keyword makes the code more difficult to read, or increases the 
risk of errors or misunderstandings.

It is quite obvious that it is easy to write code with loops + break 
within a switch.  It is equally obvious that it is easy to avoid such 
constructs - there are always ways to avoid a "break" in a loop, and if 
the code run within a switch case is complex, it is often practical to 
refactor it into a separate function.  But presumably Michael has 
reasons not do do that.
Re: Taming The Switch-Statement
#215
Author: bart
Date: Sun, 11 Oct 2026 13:39
87 lines
5327 bytes
On 11/10/2026 13:42, David Brown wrote:
> On 11/10/2026 12:58, bart wrote:


>> We don't know that, we just see the end result.
> 
> I don't think there is anything much you can say about that without 
> sidetracking to a definition of what we mean by "a problem", and then 
> doing a massive survey of lots of C programmers.
> 
> We do know that C is a massively successful programming language, used 
> by vast numbers of people, and that switch statements are common in C. 
> This is true regardless of any real or imagined "problem" with C's 
> switch statements.

I know that, despite the success, a vast amount of effort has to be 
spent to keep on top of or to get around all its problems, and there may 
yet be bugs we don't know about due to them.

I can see that from looking at other forums at the things people have 
trouble with, that wouldn't happen with a tidier and less quirky language.

> 
>>
>>>   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.
>>
>> This is the core C code for Duff's Device from Wikipedia:
>>
> 
> We know what Duff's Device is, and no one cares about your language.  It 
> is not an alternative to C in any way.

It doesn't matter. The point is that Duff's Device is always given as an 
example to show how wonderful it is to have default fall-through in C, 
even though in the vast majority of cases, 'break' has to be used to 
inhibit it.

Yet there are other ways to express the same thing using other features.

(BTW gcc gives me fall-through warnings on that Duff's example. How do 
you shut that up while keeping them for other code?)

>> That should tell you more.
> 
> We could pick a dozen different real-world languages, with a dozen 
> different kinds of switch, case, match or other multiple choice 
> construct (or lack thereof).  That should tell you that there is no 
> "right" or "wrong" choice here - there are different design choices, 
> with different pros and cons, different flexibilities and limitations, 
> and appropriate for different kinds of language and different kinds of 
> tools.

This is a line from my C compiler written in my language:

	doswitch lxsptr++^
	when 'A'..'Z', 'a'..'z', '$', '_' then ...

This is what I'd have to write to express the same thing in standard C:

   while (1)
    switch (*lxsptr++) {
    case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
    case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N':
    case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U':
    case 'V': case 'W': case 'X': case 'Y': case 'Z':
    case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
    case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
    case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u':
    case 'v': case 'w': case 'x': case 'y': case 'z':
    case '0': case '1': case '2': case '3': case '4': case '5': case '6':
    case '7': case '8': case '9': case '_': case '$': ...

So, what are the pros here? As I can't see any, only cons.

> I suggest you find something better to spend your time on than re-hashes 
> of your obsessions about what you don't like about C.

Actually it is fascinating seeing people defend ludicrously bad (to say 
nothing of unergonomic) language features like this, and vigorously 
reject any suggestions of improvement.

Re: Taming The Switch-Statement
#216
Author: bart
Date: Sun, 11 Oct 2026 13:51
42 lines
3187 bytes
On 11/10/2026 14:13, Tim Rentsch wrote:
> bart <bc@freeuk.com> writes:
> 
>> On 11/10/2026 12:26, Tim Rentsch wrote:
>>
>>> Michael S <already5chosen@yahoo.com> writes:
>>>
>>>> The cases where I want to break out of the loop from the switch in
>>>> the body of the loop are very common.
>>>
>>> That surprises me.  Can you post a representative example (and
>>> ideally not overly long)?
>>
>> An example shouldn't be necessary.  It is enough to know that
>> loop-breaks exist and are used.
> 
> It doesn't surprise me that they exist.  What surprises me is
> that they are common, in code written by someone I consider a
> competent programmer.  I don't care about what idiotic things
> are done by people who aren't competent programmers.
> 
> You might want to think about the deeper meaning of that last
> sentence.

You might also think about the deeper meaning of my comments.

You don't take a problem feature of a language design and brush it under 
the carpet.

Then, when questioned, suggest that it's very rarely used. Or when it is 
used, that they shouldn't using it because everyone should be as clever 
as you at writing convoluted code: Look how clever I am, I've never 
needed to use '(loop) break' or 'goto' ever.

(See, I even had to qualify that 'break' because 'switch' stupidly uses 
the same keyword.)

And you're ignoring my point: inside a loop is a conditional break. But 
as the language is now, you must use if-else for that condition and not 
switch. That is a flaw.

Re: Taming The Switch-Statement
#217
Author: Waldek Hebisch
Date: Sun, 11 Oct 2026 14:42
77 lines
3593 bytes
bart <bc@freeuk.com> wrote:
> On 10/10/2026 16:50, David Brown wrote:
>> On 10/10/2026 15:11, bart wrote:
> 
> Because unfortunately C's flexibility makes weird stuff possible.
> 
> C's 'switch' is truly bizarre. Below is an experiment where I took an 
> ordinary function body, and wrapped 'switch' around it with randomly 
> placed case labels.
> 
> It still worked (as I placed 'default:' near the start, and providing 
> 'm' is greater than 7), but What The Hell?
> 
> gcc with warnings says nothing useful about it.
> 
<snip>
> The fall-through feature is a minor detail.
> 
> -----------------------
> 
> static void nsieve(int m) {
>     unsigned int count = 0, i, j;
>     boolean * flags = (boolean *) malloc(m * sizeof(boolean));
>     for (i = 0; i < m; ++i) flags[i]=1;
> 
>     for (i = 2; i < m; ++i)
>         if (flags[i]) {
>             ++count;
>             for (j = i << 1; j < m; j += i)
>                    flags[j] = 0;
>     }
> 
>     free(flags);
>     printf("Primes up to %8u %8u\n", m, count);
> }
> 
> static void nsieve_sw(int m) {
>     switch (m) {
>     default:
>     case 1:
>         unsigned int count = 0, i, j;
>     case 2:
>         boolean * flags = (boolean *) malloc(m * sizeof(boolean));
>         for (i = 0; i < m; ++i)
>             case 3:
>                 flags[i]=1;
> 
>         for (i = 2; i < m; ++i)
>             if (flags[i]) {
>             case 4:
>                 ++count;
>             case 5:
>                 for (j = i << 1; j < m; j += i)
>             case 6:
>                        flags[j] = 0;
>         }
> 
>         free(flags);
>             case 7:
>         printf("Primes up to %8u %8u\n", m, count);
>     }
> }
> 

I am disappointed by gcc optimizations (at least by gcc-12).  gcc
should notice that m equal to 3 immediately leads to use of
uninitialized variable, so is undefined behaviour.  Similarly
m equal to 6.  When m equals 4 or m equals 5 then test for
containing loop will lead to use of uninitialized variable.
AFAICS m equal 1 and m equal 2 are useless.  gcc should assume
that there is no undefined behaviour, so the only remaining
case is m = 7.  So gcc could simplify this function quite a lot.
But looking at assembly shows that gcc generated actual switch
with 5 cases (corresponding to m being 3, 4, 5, 6, 7).

-- 
                              Waldek Hebisch
Re: Taming The Switch-Statement
#219
Author: Scott Lurndal
Date: Sun, 11 Oct 2026 15:29
18 lines
2056 bytes
bart <bc@freeuk.com> writes:
>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.
>

Burroughs BPL68 had EXITBLOCK, EXITCOND, EXITLOOP and EXITCASE as
mechanisms to break from nested loops, conditionals and case (switch)
statements.
Re: Taming The Switch-Statement
#220
Author: bart
Date: Sun, 11 Oct 2026 15:41
50 lines
2997 bytes
On 11/10/2026 11:58, bart wrote:
> On 10/10/2026 16:50, David Brown wrote:

> This is the core C code for Duff's Device from Wikipedia:
> 
>      switch (count % 8) {
>          case 0: *to = *from++;
>          case 7: *to = *from++;
>          case 6: *to = *from++;
>          case 5: *to = *from++;
>          case 4: *to = *from++;
>          case 3: *to = *from++;
>          case 2: *to = *from++;
>          case 1: *to = *from++;
>      }
> 
> This is the emulation of it in my language ('to' is a reserved word, and 
> that constuct is 1-based):
> 
>      goto (count rem 8| L1, L2, L3, L4, L5, L6, L7 | L0)
> 
>      L0: d^ := s++^
>      L7: d^ := s++^
>      L6: d^ := s++^
>      L5: d^ := s++^
>      L4: d^ := s++^
>      L3: d^ := s++^
>      L2: d^ := s++^
>      L1: d^ := s++^
> 
> Those labels need to be unique, but probably you won't need more than 
> one Duff's Device in any one function.

Here is it in my language after 10 minutes' work to create a 
fall-through version of my switch:

     switchf count rem 8
     when 0 then d^ := s++^
     when 7 then d^ := s++^
     when 6 then d^ := s++^
     when 5 then d^ := s++^
     when 4 then d^ := s++^
     when 3 then d^ := s++^
     when 2 then d^ := s++^
     when 1 then d^ := s++^
     end

It remains properly structured, but the block order is now important.

The feature will not be kept.
Re: Taming The Switch-Statement
#221
Author: Andrey Tarasevich
Date: Sun, 11 Oct 2026 16:01
38 lines
3210 bytes
On Sun 10/11/2026 6:33 AM, David Brown wrote:
> 
> It is quite obvious that it is easy to write code with loops + break 
> within a switch.  It is equally obvious that it is easy to avoid such 
> constructs - there are always ways to avoid a "break" in a loop, and if 
> the code run within a switch case is complex, it is often practical to 
> refactor it into a separate function.  But presumably Michael has 
> reasons not do do that.

Um... The common pattern for a "search"-style loop looks as follows

   for (/* domain condition */)
   {
     ...
     if (/* search condition */)
       break;
     ...
   }

So, loops that terminate with `break` are the mainstay of every 
competently written code. Moving the "early termination" condition into 
the loop header (i.e. lumping the search condition with the domain 
condition) is a very ugly anti-pattern in most cases. Moreover, majority 
of the loops in an average C program are such "search"-style loops, 
meaning that they do have an "early termination" condition.

Now, while overwhelming majority of my loops would use `if` to check the 
"early termination", I can imagine that there sill be cases where 
`switch` is applicable and more appropriate than an `if`. Yes, a 
`switch` can always be replaced with an `if` ladder, but being _forced_ 
to do so by a language limitation doesn't look right.

And writing a separate function just to work around a weird language 
limitation... that doesn't look right either.

-- 
Best regards,
Andrey
Re: Taming The Switch-Statement
#222
Author: bart
Date: Sun, 11 Oct 2026 16:23
96 lines
4901 bytes
On 11/10/2026 15:42, Waldek Hebisch wrote:
> bart <bc@freeuk.com> wrote:
>> On 10/10/2026 16:50, David Brown wrote:
>>> On 10/10/2026 15:11, bart wrote:
>>
>> Because unfortunately C's flexibility makes weird stuff possible.
>>
>> C's 'switch' is truly bizarre. Below is an experiment where I took an
>> ordinary function body, and wrapped 'switch' around it with randomly
>> placed case labels.
>>
>> It still worked (as I placed 'default:' near the start, and providing
>> 'm' is greater than 7), but What The Hell?
>>
>> gcc with warnings says nothing useful about it.
>>
> <snip>
>> The fall-through feature is a minor detail.
>>
>> -----------------------
>>
>> static void nsieve(int m) {
>>      unsigned int count = 0, i, j;
>>      boolean * flags = (boolean *) malloc(m * sizeof(boolean));
>>      for (i = 0; i < m; ++i) flags[i]=1;
>>
>>      for (i = 2; i < m; ++i)
>>          if (flags[i]) {
>>              ++count;
>>              for (j = i << 1; j < m; j += i)
>>                     flags[j] = 0;
>>      }
>>
>>      free(flags);
>>      printf("Primes up to %8u %8u\n", m, count);
>> }
>>
>> static void nsieve_sw(int m) {
>>      switch (m) {
>>      default:
>>      case 1:
>>          unsigned int count = 0, i, j;
>>      case 2:
>>          boolean * flags = (boolean *) malloc(m * sizeof(boolean));
>>          for (i = 0; i < m; ++i)
>>              case 3:
>>                  flags[i]=1;
>>
>>          for (i = 2; i < m; ++i)
>>              if (flags[i]) {
>>              case 4:
>>                  ++count;
>>              case 5:
>>                  for (j = i << 1; j < m; j += i)
>>              case 6:
>>                         flags[j] = 0;
>>          }
>>
>>          free(flags);
>>              case 7:
>>          printf("Primes up to %8u %8u\n", m, count);
>>      }
>> }
>>
> 
> I am disappointed by gcc optimizations (at least by gcc-12).  gcc
> should notice that m equal to 3 immediately leads to use of
> uninitialized variable, so is undefined behaviour.  Similarly
> m equal to 6.  When m equals 4 or m equals 5 then test for
> containing loop will lead to use of uninitialized variable.
> AFAICS m equal 1 and m equal 2 are useless.  gcc should assume
> that there is no undefined behaviour, so the only remaining
> case is m = 7.  So gcc could simplify this function quite a lot.
> But looking at assembly shows that gcc generated actual switch
> with 5 cases (corresponding to m being 3, 4, 5, 6, 7).
> 

My gcc 14 eliminates the entire function with -O3!

If I remove the 'static', the jumptable stays in, but it is only 5 elements.

If 'static' is left in but it is called as nsieve_sw(10000000) from 
elsewhere, then it is inlined and the switch disappears.

BTW, nsieve_sw(10000000) takes gcc -O1/2/3 0.15 seconds to run.

With BCC (needs some labels to end with ";") the full jumptable stays 
in, it is not inlined, but it also takes 0.15 seconds (when 'boolean' is 
unsigned char).

The switch and call is a one-time cost, and the benchmark is memory 
intensive, so it is kind to poor optimisers.

(But TCC takes 0.3s because locals reside in memory. Still, it is only 
2:1 slower than optimised C. My scripting language takes 0.9s when using 
a bit-array. Lua/CPython take 2.7/2.5s using default numeric type.)
Re: Taming The Switch-Statement
#224
Author: David Brown
Date: Sun, 11 Oct 2026 17:17
60 lines
4703 bytes
On 11/10/2026 18:01, Andrey Tarasevich wrote:
> On Sun 10/11/2026 6:33 AM, David Brown wrote:
>>
>> It is quite obvious that it is easy to write code with loops + break 
>> within a switch.  It is equally obvious that it is easy to avoid such 
>> constructs - there are always ways to avoid a "break" in a loop, and 
>> if the code run within a switch case is complex, it is often practical 
>> to refactor it into a separate function.  But presumably Michael has 
>> reasons not do do that.
> 
> Um... The common pattern for a "search"-style loop looks as follows
> 
>    for (/* domain condition */)
>    {
>      ...
>      if (/* search condition */)
>        break;
>      ...
>    }
> 
> So, loops that terminate with `break` are the mainstay of every 
> competently written code. Moving the "early termination" condition into 
> the loop header (i.e. lumping the search condition with the domain 
> condition) is a very ugly anti-pattern in most cases. Moreover, majority 
> of the loops in an average C program are such "search"-style loops, 
> meaning that they do have an "early termination" condition.
> 
> Now, while overwhelming majority of my loops would use `if` to check the 
> "early termination", I can imagine that there sill be cases where 
> `switch` is applicable and more appropriate than an `if`. Yes, a 
> `switch` can always be replaced with an `if` ladder, but being _forced_ 
> to do so by a language limitation doesn't look right.
> 
> And writing a separate function just to work around a weird language 
> limitation... that doesn't look right either.
> 

Certainly plenty of loops have "break" statements, especially as an 
early exit.

Sometimes code is written with big switches in a function, and the cases 
might include loops, and those loops might have break statements.  The 
question is why someone might consider this a very common situation, and 
why they might consider it a failing that the same keyword is used for a 
switch "break" and for a loop "break".  There are two possibilities I 
can imagine, but Michael may have other things in mind.  One is that the 
code is less clear than it might otherwise have been - if that is the 
case, then I think the code should be considered for re-factoring into 
separate functions if the inner loops are too complex.  The other 
possibility is that the programmer wanted to break out of the switch 
from within the middle of the inner loop.  I can imagine that happening, 
and it would currently need either a bit of extra code to do the 
"breaking" in two steps, a "goto", or refactoring into a separate 
function.  But it seems strange to me that someone would feel that was a 
common enough problem to want to have "switch break" and "loop break" be 
separate keywords, rather than go straight to a "break <label>" solution 
that would be more general.

Only Michael can, if he wants, explain what he was thinking.
Re: Taming The Switch-Statement
#225
Author: Waldek Hebisch
Date: Sun, 11 Oct 2026 17:48
87 lines
4165 bytes
bart <bc@freeuk.com> wrote:
> On 11/10/2026 15:42, Waldek Hebisch wrote:
>> bart <bc@freeuk.com> wrote:
>>> On 10/10/2026 16:50, David Brown wrote:
>>>> On 10/10/2026 15:11, bart wrote:
>>>
>>> Because unfortunately C's flexibility makes weird stuff possible.
>>>
>>> C's 'switch' is truly bizarre. Below is an experiment where I took an
>>> ordinary function body, and wrapped 'switch' around it with randomly
>>> placed case labels.
>>>
>>> It still worked (as I placed 'default:' near the start, and providing
>>> 'm' is greater than 7), but What The Hell?
>>>
>>> gcc with warnings says nothing useful about it.
>>>
>> <snip>
>>> The fall-through feature is a minor detail.
>>>
>>> -----------------------
>>>
>>> static void nsieve(int m) {
>>>      unsigned int count = 0, i, j;
>>>      boolean * flags = (boolean *) malloc(m * sizeof(boolean));
>>>      for (i = 0; i < m; ++i) flags[i]=1;
>>>
>>>      for (i = 2; i < m; ++i)
>>>          if (flags[i]) {
>>>              ++count;
>>>              for (j = i << 1; j < m; j += i)
>>>                     flags[j] = 0;
>>>      }
>>>
>>>      free(flags);
>>>      printf("Primes up to %8u %8u\n", m, count);
>>> }
>>>
>>> static void nsieve_sw(int m) {
>>>      switch (m) {
>>>      default:
>>>      case 1:
>>>          unsigned int count = 0, i, j;
>>>      case 2:
>>>          boolean * flags = (boolean *) malloc(m * sizeof(boolean));
>>>          for (i = 0; i < m; ++i)
>>>              case 3:
>>>                  flags[i]=1;
>>>
>>>          for (i = 2; i < m; ++i)
>>>              if (flags[i]) {
>>>              case 4:
>>>                  ++count;
>>>              case 5:
>>>                  for (j = i << 1; j < m; j += i)
>>>              case 6:
>>>                         flags[j] = 0;
>>>          }
>>>
>>>          free(flags);
>>>              case 7:
>>>          printf("Primes up to %8u %8u\n", m, count);
>>>      }
>>> }
>>>
>> 
>> I am disappointed by gcc optimizations (at least by gcc-12).  gcc
>> should notice that m equal to 3 immediately leads to use of
>> uninitialized variable, so is undefined behaviour.  Similarly
>> m equal to 6.  When m equals 4 or m equals 5 then test for
>> containing loop will lead to use of uninitialized variable.
>> AFAICS m equal 1 and m equal 2 are useless.  gcc should assume
>> that there is no undefined behaviour, so the only remaining
>> case is m = 7.  So gcc could simplify this function quite a lot.
>> But looking at assembly shows that gcc generated actual switch
>> with 5 cases (corresponding to m being 3, 4, 5, 6, 7).
>> 
> 
> My gcc 14 eliminates the entire function with -O3!
> 
> If I remove the 'static', the jumptable stays in, but it is only 5 elements.

Of course I removed 'static'.  A single 'static' function which is
never called should be removed.

-- 
                              Waldek Hebisch
Re: Taming The Switch-Statement
#226
Author: bart
Date: Sun, 11 Oct 2026 17:57
75 lines
5277 bytes
On 11/10/2026 18:17, David Brown wrote:
> On 11/10/2026 18:01, Andrey Tarasevich wrote:
>> On Sun 10/11/2026 6:33 AM, David Brown wrote:
>>>
>>> It is quite obvious that it is easy to write code with loops + break 
>>> within a switch.  It is equally obvious that it is easy to avoid such 
>>> constructs - there are always ways to avoid a "break" in a loop, and 
>>> if the code run within a switch case is complex, it is often 
>>> practical to refactor it into a separate function.  But presumably 
>>> Michael has reasons not do do that.
>>
>> Um... The common pattern for a "search"-style loop looks as follows
>>
>>    for (/* domain condition */)
>>    {
>>      ...
>>      if (/* search condition */)
>>        break;
>>      ...
>>    }
>>
>> So, loops that terminate with `break` are the mainstay of every 
>> competently written code. Moving the "early termination" condition 
>> into the loop header (i.e. lumping the search condition with the 
>> domain condition) is a very ugly anti-pattern in most cases. Moreover, 
>> majority of the loops in an average C program are such "search"-style 
>> loops, meaning that they do have an "early termination" condition.
>>
>> Now, while overwhelming majority of my loops would use `if` to check 
>> the "early termination", I can imagine that there sill be cases where 
>> `switch` is applicable and more appropriate than an `if`. Yes, a 
>> `switch` can always be replaced with an `if` ladder, but being 
>> _forced_ to do so by a language limitation doesn't look right.
>>
>> And writing a separate function just to work around a weird language 
>> limitation... that doesn't look right either.
>>
> 
> Certainly plenty of loops have "break" statements, especially as an 
> early exit.
> 
> Sometimes code is written with big switches in a function, and the cases 
> might include loops, and those loops might have break statements.  The 
> question is why someone might consider this a very common situation, and 
> why they might consider it a failing that the same keyword is used for a 
> switch "break" and for a loop "break".  There are two possibilities I 
> can imagine, but Michael may have other things in mind.  One is that the 
> code is less clear than it might otherwise have been - if that is the 
> case, then I think the code should be considered for re-factoring into 
> separate functions if the inner loops are too complex.  The other 
> possibility is that the programmer wanted to break out of the switch 
> from within the middle of the inner loop.  I can imagine that happening, 
> and it would currently need either a bit of extra code to do the 
> "breaking" in two steps, a "goto", or refactoring into a separate 
> function.  But it seems strange to me that someone would feel that was a 
> common enough problem to want to have "switch break" and "loop break" be 
> separate keywords, rather than go straight to a "break <label>" solution 
> that would be more general.
> 
> Only Michael can, if he wants, explain what he was thinking.

It sounds like he's pressurised into doing so. Maybe so that he can be 
lectured on how to it 'properly'.

'break' to quit a loop early is part of the language, so why shouldn't 
someone make use it?

It just its use can be interfered with when 'switch' is involved.

That that happens and needs a workaround, is not satisfactory. The issue 
exists 100% because of sharing the 'break' keyword for two different 
purposes.

> 
Re: Taming The Switch-Statement
#227
Author: bart
Date: Sun, 11 Oct 2026 18:10
68 lines
3923 bytes
On 11/10/2026 18:48, Waldek Hebisch wrote:
> bart <bc@freeuk.com> wrote:
>> On 11/10/2026 15:42, Waldek Hebisch wrote:
>>> bart <bc@freeuk.com> wrote:

>>>> static void nsieve_sw(int m) {
>>>>       switch (m) {
>>>>       default:
>>>>       case 1:
>>>>           unsigned int count = 0, i, j;
>>>>       case 2:
>>>>           boolean * flags = (boolean *) malloc(m * sizeof(boolean));
>>>>           for (i = 0; i < m; ++i)
>>>>               case 3:
>>>>                   flags[i]=1;
>>>>
>>>>           for (i = 2; i < m; ++i)
>>>>               if (flags[i]) {
>>>>               case 4:
>>>>                   ++count;
>>>>               case 5:
>>>>                   for (j = i << 1; j < m; j += i)
>>>>               case 6:
>>>>                          flags[j] = 0;
>>>>           }
>>>>
>>>>           free(flags);
>>>>               case 7:
>>>>           printf("Primes up to %8u %8u\n", m, count);
>>>>       }
>>>> }
>>>>
>>>
>>> I am disappointed by gcc optimizations (at least by gcc-12).  gcc
>>> should notice that m equal to 3 immediately leads to use of
>>> uninitialized variable, so is undefined behaviour.  Similarly
>>> m equal to 6.  When m equals 4 or m equals 5 then test for
>>> containing loop will lead to use of uninitialized variable.
>>> AFAICS m equal 1 and m equal 2 are useless.  gcc should assume
>>> that there is no undefined behaviour, so the only remaining
>>> case is m = 7.  So gcc could simplify this function quite a lot.
>>> But looking at assembly shows that gcc generated actual switch
>>> with 5 cases (corresponding to m being 3, 4, 5, 6, 7).
>>>
>>
>> My gcc 14 eliminates the entire function with -O3!
>>
>> If I remove the 'static', the jumptable stays in, but it is only 5 elements.
> 
> Of course I removed 'static'.  A single 'static' function which is
> never called should be removed.

If I do this:

   static void nsieve_sw(int m) { ... }

   static void* abc = nsieve_sw;

   int main(void) {
       abc = nsieve_sw;
   }

then nsieve_sw is never called, but it is not removed. It /is/ removed 
if 'abc' is moved into main().

Apart from that anomaly, only the potential to call even a static 
function needs to exist, say by taking its address. The function might 
never be called though.
Re: Taming The Switch-Statement
#235
Author: Keith Thompson
Date: Sun, 11 Oct 2026 21:04
55 lines
3765 bytes
bart <bc@freeuk.com> writes:
> On 11/10/2026 03:55, Keith Thompson wrote:
>> 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.
>
>>>> 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,
>
> So how would you do it: remove existing switch completely and replace
> with the new version?

No, I'd leave it alone.

C's switch statement is, like C as a whole, "quirky, flawed, and
an enormous success" (Dennis Ritchie said that).

You want to add a new construct that differs from switch only in
that it doesn't have implicit fallthrough.  You think the existence
of fallthrough behavior, or of any flexibility that you see as
excessive, is a problem that needs to be fixed.  I don't.

C's switch statement is *almost always* used to implement the same
patterns that can be implemented using Pascal's case statement.
(A minor difference is case ranges, which are proposed for C2y.)

You want to add a "newswitch" construct (presumably with a better
name) that's just like "switch" except that there's no fallthrough.
It would add no real expressive power.  (I'm tempted to propose
calling it "static switch".  To be clear, that's a joke.)

C already has such a construct, called "switch and don't forget to
write break after each case".  There are existing tools that help
with that.

Would it have been better if C's switch statement had behaved
like your "newswitch"?  Yeah, probably.  If I were inventing a new
language, I probably wouldn't copy that particular design decision
from C.  Fallthrough *is* useful sometimes, so I'd probably suggest
adding a "fallthrough" keyword.

But the existing switch statement is good enough, and the cost of
"fixing" it would be much higher than the minimal benefits.

-- 
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
#237
Author: Lawrence D’Oliveiro
Date: Sun, 11 Oct 2026 21:12
54 lines
4450 bytes
On 11 Oct 2026 10:14:15 GMT, Stefan Ram wrote:

> On Sat, 10 Oct 2026 22:58:15 -0000 (UTC), 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/>
>
> Assuming a "break" will leave an "if" in C is an error of someone
> who has not learned C yet ...

These were C experts -- they were software engineers working at AT&T
after all.

Bear in mind Bruce Sterling is not a C expert, or even a programming
expert. I have looked at several descriptions of the nature of the
bug, and I couldn’t find any (to link to) that were any better than
his.

The most natural interpretation I can think of is that the break
statement wasn’t supposed to cut short the if-statement as such; it
was meant to terminate a surrounding loop. That would have worked,
except that this particular break-statement was inside a
switch-statement in that loop, so all it did was cut short the
switch-statement. I think the surrounding loop was then left to repeat
endlessly without reaching any exit condition, which was the cause of
the failure.
Re: Taming The Switch-Statement
#238
Author: Lawrence D’Oliveiro
Date: Sun, 11 Oct 2026 21:16
15 lines
2198 bytes
On Sun, 11 Oct 2026 05:52:51 -0000 (UTC), Waldek Hebisch wrote:

> AFAICS Pascal-style 'case' + 'goto' that can jump inside constructs
> can do everthing C 'switch' can do.

There is an interesting result known as the “Structure Theorem”, which
proves that any kind of control structure can be implemented by
putting your entire program inside a large switch-statement within a
loop and using state variables to control which path is taken each
time round the loop -- with no gotos anywhere!

Of course, since it can be hard to discern the relationship between
one switch-branch being executed on one loop iteration and whatever
switch-branch is entered on the next iteration, the result is still a
form of spaghetti code ...
Re: Taming The Switch-Statement
#239
Author: Lawrence D’Oliveiro
Date: Sun, 11 Oct 2026 21:26
82 lines
4232 bytes
On Sat, 10 Oct 2026 00:25:54 -0000 (UTC), I 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.
>
> 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.

Here’s an example that matches the type of the match-expression (not
its value) against various event subclasses:

    events = iter(self.ws.events())
    while True :
        event = next(events, None)
        if event == None :
            break
        match event :
            case wsevents.AcceptConnection() :
                self.logger.debug("connection accepted")
            #end case

            case wsevents.RejectConnection() :
                raise RuntimeError \
                  (
                    "WebSockets connection rejected: code %d" % event.status_code
                  )
            #end case

            case wsevents.CloseConnection() :
                self.logger.debug("connection closing")
                if not self.closing :
                    self.closing = True
                    if ASYNC :
                        await self.sock.sendall(self.sock, self.ws.send(event.response()))
                    else :
                        self.sock.sendall(self.sock, self.ws.send(event.response()))
                    #end if
                #end if
            #end case

            case wsevents.Ping() :
                if ASYNC :
                    await self.sock.sendall(self.ws.send(event.response()))
                else :
                    self.sock.sendall(self.ws.send(event.response()))
                #end if
            #end case

            case wsevents.TextMessage() :
                self.partial += event.data
                if not event.message_finished :
                    break
                if self.partial != "" :
                    result = json.loads(self.partial)
                    self.partial = ""
                else :
                    result = None
                #end if
                yield result
            #end case

            case _ :
                raise RuntimeError \
                  (
                        "unexpected WebSocket event %s -- %s"
                    %
                        (type(event).__name__, repr(event))
                  )
            #end case
        #end match
    #end while

It is permissible to mix all the different kinds of matches in
different case-clauses within the same match-statement.

I’m still getting used to the match-statement, and I’m currently
thinking of dropping the “#end case” line, since each case-clause is
implicitly terminated by the following one (or the end of the
match-statement) anyway. The “#end match” will stay, of course.
Re: Taming The Switch-Statement
#240
Author: Keith Thompson
Date: Sun, 11 Oct 2026 21:28
37 lines
3276 bytes
bart <bc@freeuk.com> writes:
[...]
> 'break' to quit a loop early is part of the language, so why shouldn't
> someone make use it?

Agreed.  (There are coding styles that require loops to exit only at the
bottom, but that's not what we're talking about.)

> It just its use can be interfered with when 'switch' is involved.

Yes.  Everyone here knows that, and knew it before you started talking
about it.

Michael S wrote above that "The cases where I want to break out of
the loop from the switch in the body of the loop are very common."
Tim Rentsch questioned the "very common" part of that, and asked
for an example.  You jumped in and asserted that an example isn't
necessary, because you misunderstood what was being said.  *Of
course* there are cases where someone might want to break out of
a loop from a nested switch.

> That that happens and needs a workaround, is not satisfactory. The
> issue exists 100% because of sharing the 'break' keyword for two
> different purposes.

Yes, the overloading of the "break" keyword can be inconvenient.
It makes it difficult to break out of a loop from within a switch
statement.  Again, everyone here knows that.

Breaking out of an outer loop from within an inner loop is just
as much of a problem.  "break NAME;" proposed for C2y, would solve
both problems.  (I just found out that recent versions of gcc and
clang support this as an extension or with "-std=c2y".)

-- 
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
#241
Author: bart
Date: Sun, 11 Oct 2026 21:36
65 lines
3453 bytes
On 11/10/2026 02:12, bart wrote:

> 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;'.

It might have more problems than that, due to not having 'closure'. That 
is, delimiting that might be done by 'end' or via indents in some 
languages, or by '}' here.

I would prefer not to have enclose the whole body in braces. But as it 
is, then here:

      newswitch()
      case          // 1
          newswitch()
          case
          case      // 3
      case          // 4

it's not clear, when there is no 'else' part, whether case(4) continues 
that second switch and from case(3) or the first and case(1), and there 
is no way to disambiguate.

OK, not a big problem, it's not hard to fix. Fortunately I'm not going 
to implement it.

(BTW I had a look at an old versions of my language, and it seems it 
didn't acquire 'switch' until quite late.

Instead there was another, more flexible statement:

* This worked for scalar types ints, floats and pointers

* Test values could be runtime expressions

* Comparisons were done sequentially

* The whole thing could return a value and be used in expressions, or
   be the last statement of a value-returning function.

I believe 'switch' was introduced as an explicit streamlined version with:

* Only 'int' expressions

* Test values had to be compile-time constants

* Comparisons were expected to be done in parallel, and via
   a jump-table.

Having two forms was considered simpler than the compiler trying to 
analyse the one kind of statement, and silently /not/ using a jumptable 
due to some oversight.)
Re: Taming The Switch-Statement
#242
Author: bart
Date: Sun, 11 Oct 2026 22:02
56 lines
3893 bytes
On 11/10/2026 22:28, Keith Thompson wrote:
> bart <bc@freeuk.com> writes:
> [...]
>> 'break' to quit a loop early is part of the language, so why shouldn't
>> someone make use it?
> 
> Agreed.  (There are coding styles that require loops to exit only at the
> bottom, but that's not what we're talking about.)
> 
>> It just its use can be interfered with when 'switch' is involved.
> 
> Yes.  Everyone here knows that, and knew it before you started talking
> about it.
> 
> Michael S wrote above that "The cases where I want to break out of
> the loop from the switch in the body of the loop are very common."
> Tim Rentsch questioned the "very common" part of that, and asked
> for an example.  You jumped in and asserted that an example isn't
> necessary, because you misunderstood what was being said.  *Of
> course* there are cases where someone might want to break out of
> a loop from a nested switch.

You're missing the undercurrent, which is a tone of disapproval and 
disbelief.

But we'll find out if and when examples are ever posted.

However you may want to consider that examples are rare, or even 
non-existent, /because/ it's not possible to do! So using 'switch' is 
avoided or some other workaround is found.

Michael S actually said this:

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

This expresses a desire to do so.

> Breaking out of an outer loop from within an inner loop is just
> as much of a problem.

A less common one but when it happens it will be an actual problem and 
not an artificial one.

>  "break NAME;" proposed for C2y, would solve
> both problems.  (I just found out that recent versions of gcc and
> clang support this as an extension or with "-std=c2y".)

OK. I'd rather have a solution that doesn't involve inventing names.

Does this also fix the break-out-of-a-loop-from-inside-switch issue? In 
that case just 'break for/while' might do!

You know, a little bit like using a different keyword for loops/non-loops.

Re: Taming The Switch-Statement
#243
Author: bart
Date: Sun, 11 Oct 2026 22:05
36 lines
2879 bytes
On 11/10/2026 22:04, Keith Thompson wrote:
> bart <bc@freeuk.com> writes:
>> On 11/10/2026 03:55, Keith Thompson wrote:
>>> 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.
>>
>>>>> 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,
>>
>> So how would you do it: remove existing switch completely and replace
>> with the new version?
> 
> No, I'd leave it alone.
> 
> C's switch statement is, like C as a whole, "quirky, flawed, and
> an enormous success" (Dennis Ritchie said that).

Yeah, like anyone had a choice in the matter!

> You want to add a new construct that differs from switch only in
> that it doesn't have implicit fallthrough.  You think the existence
> of fallthrough behavior, or of any flexibility that you see as
> excessive, is a problem that needs to be fixed.  I don't.

So you don't really get it. That's fine.

Re: Taming The Switch-Statement
#244
Author: Jon Ribbens
Date: Sun, 11 Oct 2026 22:12
17 lines
1740 bytes
On 2026-10-11, Lawrence D’Oliveiro <ldo@nz.invalid> wrote:
> Here’s an example that matches the type of the match-expression (not
> its value) against various event subclasses:
>
>     events = iter(self.ws.events())
>     while True :
>         event = next(events, None)
>         if event == None :
>             break

Um.

Why would you do that and not:

    for event in self.ws.events():

?
Re: Taming The Switch-Statement
#245
Author: Keith Thompson
Date: Sun, 11 Oct 2026 22:35
61 lines
4018 bytes
bart <bc@freeuk.com> writes:
> On 11/10/2026 13:42, David Brown wrote:
[...]
>> We know what Duff's Device is, and no one cares about your
>> language.  It is not an alternative to C in any way.
>
> It doesn't matter. The point is that Duff's Device is always given as
> an example to show how wonderful it is to have default fall-through in
> C, even though in the vast majority of cases, 'break' has to be used
> to inhibit it.

No, it is not.

Here's what Tom Duff himself wrote about it in 1988:

    Disgusting, no?  But it compiles and runs just fine.  I feel
    a combination of pride and revulsion at this discovery.  If no
    one's thought of it before, I think I'll name it after myself.

    It amazes me that after 10 years of writing C there are still
    little corners that I haven't explored fully.  (Actually, I have
    another revolting way to use switches to implement interrupt
    driven state machines but it's too horrid to go into.)

    Many people (even bwk?) have said that the worst feature of C is
    that switches don't break automatically before each case label.
    This code forms some sort of argument in that debate, but I'm
    not sure whether it's for or against.

https://doc.cat-v.org/bell_labs/duffs_device

> Yet there are other ways to express the same thing using other features.

Are there?  Duff himself was unable to find a more efficient
algorithm -- and this was in a (rare) context where efficiency
was more important than clarity.

> (BTW gcc gives me fall-through warnings on that Duff's example. How do
> you shut that up while keeping them for other code?)

The ways to inhibit gcc's warnings about implicit fallthrough have
already been discussed in this thread.  But you've said before
that you don't care about gcc, so I won't try yet again to teach you
about how to use it.

[...]

> Actually it is fascinating seeing people defend ludicrously bad (to
> say nothing of unergonomic) language features like this, and
> vigorously reject any suggestions of improvement.

When someone here explains how something works, you think they're
vigorously defending it.

Yes, the implicit fallthrough in C's switch statements a misfeature.
I do not support suggestions to "fix" it because no such fix would
actually improve the language.

-- 
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
#251
Author: Keith Thompson
Date: Sun, 11 Oct 2026 23:29
51 lines
3646 bytes
bart <bc@freeuk.com> writes:
> On 11/10/2026 22:28, Keith Thompson wrote:
[...]
> You're missing the undercurrent, which is a tone of disapproval and
> disbelief.

I was responding to what you wrote, not to some "undercurrent".

Missing it?  I'm practically drowning in it.

You're missing the fact that the problems you keep complaining
about are things that (essentially) everyone was already aware of.

You seem unable to understand that the rest of aren't as angry about
fallthrough as you are, and that we might have valid reasons for
not being angry about it.  You seem to think that anyone who is not
outraged that C hasn't added a version of switch that doesn't have
fallthrough simply doesn't understand what you're saying.

[...]

>> Breaking out of an outer loop from within an inner loop is just
>> as much of a problem.
>
> A less common one but when it happens it will be an actual problem and
> not an artificial one.
>
>>  "break NAME;" proposed for C2y, would solve
>> both problems.  (I just found out that recent versions of gcc and
>> clang support this as an extension or with "-std=c2y".)

[...]

> Does this also fix the break-out-of-a-loop-from-inside-switch issue?

It fixes it in the sense that both loops and switch statements can be
named, and a break or continue can optionally refer to the name of the
targeted loop or switch statement.  Of course it doesn't automatically
fix existing code.

> In that case just 'break for/while' might do!

That would work for a "for" within a "while", or a "while" within
a "for", but not for a "while" within a "while" or a "for" within
a "for".

There is ample precedent for named loops in other languages.

-- 
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
#252
Author: Waldek Hebisch
Date: Sun, 11 Oct 2026 23:38
25 lines
2370 bytes
Lawrence D’Oliveiro <ldo@nz.invalid> wrote:
> On Sun, 11 Oct 2026 05:52:51 -0000 (UTC), Waldek Hebisch wrote:
> 
>> AFAICS Pascal-style 'case' + 'goto' that can jump inside constructs
>> can do everthing C 'switch' can do.
> 
> There is an interesting result known as the “Structure Theorem”, which
> proves that any kind of control structure can be implemented by
> putting your entire program inside a large switch-statement within a
> loop and using state variables to control which path is taken each
> time round the loop -- with no gotos anywhere!
> 
> Of course, since it can be hard to discern the relationship between
> one switch-branch being executed on one loop iteration and whatever
> switch-branch is entered on the next iteration, the result is still a
> form of spaghetti code ...

Unlike structure theorem the above does not need extra state variable.

BTW: Good compiler should be able to eliminate state varible and
recreate original spagetti, but no compiler that I use is good
enough.

-- 
                              Waldek Hebisch
Re: Taming The Switch-Statement
#257
Author: David Brown
Date: Mon, 12 Oct 2026 05:05
66 lines
4987 bytes
On 11/10/2026 19:57, bart wrote:
> On 11/10/2026 18:17, David Brown wrote:

>> Only Michael can, if he wants, explain what he was thinking.
> 
> It sounds like he's pressurised into doing so. Maybe so that he can be 
> lectured on how to it 'properly'.

The "pressure" is just because people are curious for more detail. 
Michael is an experienced C programmer, but we all work in slightly 
different ways on slightly different kinds of code bases.  I can't think 
why breaking out of loops within switch cases would be "very common", 
but I have no reason to suspect Michael was not writing code "properly". 
  I can't think why such code - common or not - would be problematic, or 
why having two different "break" keywords or constructs would be better 
for his code.  That's why I would like Michael to give more details - 
not to tell him his "wrong", but to learn more about his coding.

> 
> 'break' to quit a loop early is part of the language, so why shouldn't 
> someone make use it?

I think most C programmers do, at least occasionally.

> 
> It just its use can be interfered with when 'switch' is involved.
> 

I personally have never found an issue there.  "break" breaks out of the 
innermost loop or switch.  If you write switch statements that are 
intermingled with loops in a non-structured manner, I am sure things get 
difficult and unclear.  Since I do not write code with such 
intermingling, I have not had any such problems.  Other people may 
choose to intermingle switches and loops, and may then have issues as a 
result, but I have not seen this in real code.

> That that happens and needs a workaround, is not satisfactory. The issue 
> exists 100% because of sharing the 'break' keyword for two different 
> purposes.
> 

First, there is no indication that conflicts between switch and loop 
"break" occurs in real code, or what the nature of such issues are. 
(Michael's brief comments are not enough information.)  Secondly, there 
is no indication that this "needs a workaround" - especially as there is 
no definition of what might be called a "workaround".  Usually you use 
the term to mean C code that you want to complain about.  Thirdly, the 
keyword "break" is not being used for two different purposes - it is 
being used for the same purpose in two different control structures.

It is well established that there are occasions where you have nested 
control structures, where it would be useful to be able to break out of 
an outer structure.  In C, "break" by itself does not handle such cases, 
and thus additional code is needed (what you call a "workaround", and 
other people call "writing code") - something people have managed to do 
for decades.  It is well established that at least some programmers 
would find it convenient to have some kind of multi-level or labelled 
"break" to let such cases be handled in a neater way, and there are 
proposals to add such a feature to C.  This is a general situation with 
nested control structures, and not in any way specific to switches or 
mixes of switches and loops - almost certainly, nested loops are the 
primary use-case.



Re: Taming The Switch-Statement
#258
Author: David Brown
Date: Mon, 12 Oct 2026 05:22
68 lines
4518 bytes
On 12/10/2026 00:05, bart wrote:
> On 11/10/2026 22:04, Keith Thompson wrote:
>> bart <bc@freeuk.com> writes:
>>> On 11/10/2026 03:55, Keith Thompson wrote:
>>>> 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.
>>>
>>>>>> 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,
>>>
>>> So how would you do it: remove existing switch completely and replace
>>> with the new version?
>>
>> No, I'd leave it alone.
>>
>> C's switch statement is, like C as a whole, "quirky, flawed, and
>> an enormous success" (Dennis Ritchie said that).
> 
> Yeah, like anyone had a choice in the matter!

There are /no/ programming languages that are successful, but not 
"quirky and flawed" - though there will always be differing opinions on 
what aspects are "quirky", and what aspects are "flawed".  As long as 
there is more than one person involved, writing code in more than one 
way for more than one task, this is inevitable.

The conflicts you have with people here do not stem from the quirks or 
flaws that you see in the C language.  They stem from your totally 
unjustified belief that others do not see C as quirky and flawed - your 
arrogant and megalomanic belief that you alone see its quirks and flaws, 
and that you alone can "fix" them.

The rest of us know that C is a very successful language, and can use it 
to write good and useful code.  Some people here write in C because they 
like the language, some because it is the only language they can use 
(for one of many possible reasons).  I have never met a C programmer who 
does not think the language would have been better with certain changes 
- but I have never met a programmer of /any/ language who does not have 
ideas about how the language could have been better for their use.

> 
>> You want to add a new construct that differs from switch only in
>> that it doesn't have implicit fallthrough.  You think the existence
>> of fallthrough behavior, or of any flexibility that you see as
>> excessive, is a problem that needs to be fixed.  I don't.
> 
> So you don't really get it. That's fine.
> 

So now you can drop it, along with all your other complaints about the C 
language and tools people use with it?

Alternatively, you are free to write proposals for the C standards 
committee, or take part in their discussions, aiming to actually change 
the things you so passionately insist need fixing.



Re: Taming The Switch-Statement
#259
Author: Waldek Hebisch
Date: Mon, 12 Oct 2026 07:01
79 lines
4070 bytes
bart <bc@freeuk.com> wrote:
> On 11/10/2026 18:48, Waldek Hebisch wrote:
>> bart <bc@freeuk.com> wrote:
>>> On 11/10/2026 15:42, Waldek Hebisch wrote:
>>>> bart <bc@freeuk.com> wrote:
> 
>>>>> static void nsieve_sw(int m) {
>>>>>       switch (m) {
>>>>>       default:
>>>>>       case 1:
>>>>>           unsigned int count = 0, i, j;
>>>>>       case 2:
>>>>>           boolean * flags = (boolean *) malloc(m * sizeof(boolean));
>>>>>           for (i = 0; i < m; ++i)
>>>>>               case 3:
>>>>>                   flags[i]=1;
>>>>>
>>>>>           for (i = 2; i < m; ++i)
>>>>>               if (flags[i]) {
>>>>>               case 4:
>>>>>                   ++count;
>>>>>               case 5:
>>>>>                   for (j = i << 1; j < m; j += i)
>>>>>               case 6:
>>>>>                          flags[j] = 0;
>>>>>           }
>>>>>
>>>>>           free(flags);
>>>>>               case 7:
>>>>>           printf("Primes up to %8u %8u\n", m, count);
>>>>>       }
>>>>> }
>>>>>
>>>>
>>>> I am disappointed by gcc optimizations (at least by gcc-12).  gcc
>>>> should notice that m equal to 3 immediately leads to use of
>>>> uninitialized variable, so is undefined behaviour.  Similarly
>>>> m equal to 6.  When m equals 4 or m equals 5 then test for
>>>> containing loop will lead to use of uninitialized variable.
>>>> AFAICS m equal 1 and m equal 2 are useless.  gcc should assume
>>>> that there is no undefined behaviour, so the only remaining
>>>> case is m = 7.  So gcc could simplify this function quite a lot.
>>>> But looking at assembly shows that gcc generated actual switch
>>>> with 5 cases (corresponding to m being 3, 4, 5, 6, 7).
>>>>
>>>
>>> My gcc 14 eliminates the entire function with -O3!
>>>
>>> If I remove the 'static', the jumptable stays in, but it is only 5 elements.
>> 
>> Of course I removed 'static'.  A single 'static' function which is
>> never called should be removed.
> 
> If I do this:
> 
>   static void nsieve_sw(int m) { ... }
> 
>   static void* abc = nsieve_sw;
> 
>   int main(void) {
>       abc = nsieve_sw;
>   }
> 
> then nsieve_sw is never called, but it is not removed. It /is/ removed 
> if 'abc' is moved into main().

Another missing optimization.
 
> Apart from that anomaly, only the potential to call even a static 
> function needs to exist, say by taking its address. The function might 
> never be called though.

Sure, if compiler can not decide (say due to taken address) if a
function is called, then it should keep it.  But the case above is
an easy one.  And in other contexts gcc actually can do transfomations
that require rather complex reasoning to justify.

-- 
                              Waldek Hebisch
Re: Taming The Switch-Statement
#260
Author: bart
Date: Mon, 12 Oct 2026 10:42
105 lines
4548 bytes
On 12/10/2026 06:22, David Brown wrote:
> On 12/10/2026 00:05, bart wrote:

>> So you don't really get it. That's fine.
>>
> 
> So now you can drop it, along with all your other complaints about the C 
> language and tools people use with it?

My opinions haven't changed at all. KT doesn't care because he doesn't 
understand the importance of having properly designed features. Probably 
he hasn't been involved in having to process somebody else's source code 
or having to translate it or port it.

I have an old tool which /visualises/ C source code by trying to express 
it in my syntax. It is not a formal transpiler: the semantics are not 
translated, just the shape of the code.

Still, the transformation is usually startlingly clear compared with the 
original. Anyway I applied it to two examples, first:

     switch (a) {
     case 1: 10; break;
     case 2: 20; break;
     default: 30;
     }

The output is:

     switch a
     when 1 then
         10
     when 2 then
         20
     else
         30
     end

Notice there are no breaks (which don't exist in my syntax). This is the 
second:

     switch (a) {
     default:
         if (b) {
             case 1: 10; break;
             case 2: 20; break;
         }
     }

The ") {" had to present as the tool requires the switch body to be a 
compound statement. The output is:

     switch a
     else
         if b then

         end
     end

This generated error messages about case-statement not being supported 
(being out of place).

But it doesn't look right does it?. Maybe a better version could express 
switch using gotos and arrays of label-pointers, but this would be 
disastrous for examples like the first.

I then tried Duff's example for fun, and it produced this:

     switch count rem 8
     when 0 then
         to^ := (from++)^
         fallthrough
     when 7 then
         to^ := (from++)^
         fallthrough
     when 6 then
         to^ := (from++)^
         fallthrough
     when 5 then
         to^ := (from++)^
         fallthrough
     when 4 then
         to^ := (from++)^
         fallthrough
     when 3 then
         to^ := (from++)^
         fallthrough
     when 2 then
         to^ := (from++)^
         fallthrough
     when 1 then
         to^ := (from++)^
     end

I'm surprised that it detected fall-through, but probably only in the 
simplest cases (non-empty block not ending in 'break').

'fallthrough' doesn't exist in my syntax so here it must just be a hint.


> Alternatively, you are free to write proposals for the C standards 
> committee, or take part in their discussions, aiming to actually change 
> the things you so passionately insist need fixing.
I'll be long dead before anything happens. It's taken most of my 
lifetime before even a no-brainer like binary literals became official.
Re: Taming The Switch-Statement
#261
Author: Tim Rentsch
Date: Mon, 12 Oct 2026 11:03
22 lines
2542 bytes
Keith Thompson <Keith.S.Thompson+u@gmail.com> writes:

> bart <bc@freeuk.com> writes:
> [...]
>
>> 'break' to quit a loop early is part of the language, so why shouldn't
>> someone make use it?
>
> Agreed.  (There are coding styles that require loops to exit only at the
> bottom, but that's not what we're talking about.)
>
>> It just its use can be interfered with when 'switch' is involved.
>
> Yes.  Everyone here knows that, and knew it before you started talking
> about it.
>
> Michael S wrote above that "The cases where I want to break out of
> the loop from the switch in the body of the loop are very common."
> Tim Rentsch questioned the "very common" part of that, and asked
> for an example.  [...]

I didn't question it.  I just said it surprised me.
Re: Taming The Switch-Statement
#263
Author: bart
Date: Mon, 12 Oct 2026 13:37
197 lines
8720 bytes
On 12/10/2026 06:05, David Brown wrote:
> On 11/10/2026 19:57, bart wrote:
>> On 11/10/2026 18:17, David Brown wrote:
> 
>>> Only Michael can, if he wants, explain what he was thinking.
>>
>> It sounds like he's pressurised into doing so. Maybe so that he can be 
>> lectured on how to it 'properly'.
> 
> The "pressure" is just because people are curious for more detail. 
> Michael is an experienced C programmer, but we all work in slightly 
> different ways on slightly different kinds of code bases.  I can't think 
> why breaking out of loops within switch cases would be "very common", 
> but I have no reason to suspect Michael was not writing code "properly". 
>   I can't think why such code - common or not - would be problematic, or 
> why having two different "break" keywords or constructs would be better 
> for his code.  That's why I would like Michael to give more details - 
> not to tell him his "wrong", but to learn more about his coding.
> 
>>
>> 'break' to quit a loop early is part of the language, so why shouldn't 
>> someone make use it?
> 
> I think most C programmers do, at least occasionally.
> 
>>
>> It just its use can be interfered with when 'switch' is involved.
>>
> 
> I personally have never found an issue there.  "break" breaks out of the 
> innermost loop or switch.  If you write switch statements that are 
> intermingled with loops in a non-structured manner, I am sure things get 
> difficult and unclear.  Since I do not write code with such 
> intermingling, I have not had any such problems.

What do mean by 'intermingled' - nested? That's how structured 
programming works!

Otherwise there is no intermingling in this example:

     for (i=0; i < N; ++i) {
         x = A[i];
         if (x == 5 || x == 6 || x == 10 || x == 11) break;

         switch (A[i]) {
         case 5: case 6: case 10: case 11: break;   // ??
         }
     }

The loop body shows two ways of aborting the loop when an exit condition 
is detected:

* Using an if-statement and 'break'

* Using a switch-statement and ... break?

The second doesn't work because 'break' now shadows its outer meaning. 
Both would otherwise be reasonable choices for this logic.

Here's another example:

     for (i=0; i < N; ++i) {
         if (A[i] == 1)
             if (!f()) break;
         else if (A[i] == 2)
             if (!g()) break;
         else
             if (!h()) break;
     }

Here, someone might notice that 'switch' suits this pattern better than 
an if-else chain. So they try this:

     for (i=0; i < N; ++i) {
         switch (A[i]) {
         case 1:
             if (!f()) break;
         case 2:
             if (!g()) break;
         default:
             if (!h()) break;
         }
     }

This is valid C still, but it doesn't have the same behaviour.

Maybe, some compilers with certain options may point out something about 
fall-through, so you're aware something's amiss, but it doesn't get 
around the problem: you can't simply swap if-else chains with switch 
even when the latter is a better fit.

This is a definite flaw in the language.


>> That that happens and needs a workaround, is not satisfactory. The 
>> issue exists 100% because of sharing the 'break' keyword for two 
>> different purposes.
>>

> First, there is no indication that conflicts between switch and loop 
> "break" occurs in real code, or what the nature of such issues are. 

As I said, they CAN'T occur in finished code, since some other approach 
has had to be used. You won't know if the conflicts have occurred!

> (Michael's brief comments are not enough information.)  Secondly, there 
> is no indication that this "needs a workaround" - especially as there is 
> no definition of what might be called a "workaround".  Usually you use 
> the term to mean C code that you want to complain about.  Thirdly, the 
> keyword "break" is not being used for two different purposes - it is 
> being used for the same purpose in two different control structures.

One is for loops to stop iteration, it is optional, and tends to be used 
sparingly.

The other is for switch, it is nearly always necessary for the common 
pattern of switch, and is needed because otherwise the language leaves 
you stranded in the middle of a switch statement. There is no iteration 
involved.

Does that sound about the same?

> It is well established that there are occasions where you have nested 
> control structures, where it would be useful to be able to break out of 
> an outer structure.  In C, "break" by itself does not handle such cases, 
> and thus additional code is needed (what you call a "workaround", and 
> other people call "writing code")

People keep bringing this up. Yes, that's an annoyance too, but it is 
genuinely rare.

BTW I looked at the sources for one of my projects (in my language) to 
see whether breaking a loop from switch ever occurred. I found it the 
very first instance! Then I kept finding more.

This is the outline of the first example:

     while pmtype := nextcmdparam(paramno, name, value, "m") do
         case pmtype
         when pm_option then
         when pm_sourcefile then
             if passlevel in [run_pass, runpcl_pass] then
                 exit

'case' is a sister statement to 'switch' and has the same syntax. It's 
used for more general cases usually with a small number of branches.

My 'break' statement is called 'exit'. Number two:

     do
         lex()           !first symbol on line
         case lx.symbol
         when eofsym then
         when kendsym then
             exit

There are loads more. This next is an example of breaking out of two 
loop levels:

     while wt do
         while w do
             if ... then
                 exit all

It is nearly always all the loops, so I simply write 'all' (an alias for 
0 which denotes the outermost loop without needing to count). There are 
two such 'exit all' in this 35Kloc project; all other exits are for one 
level only.

Here's one more loop/switch example, but with a twist:

     docase flags^
     when 'S' then
     when 'U' then
     else
         exit
     end

'docase' and 'doswitch' are looping forms, which are very common in my 
programs. This one is the equivalent of this in C:

    while (1) {
       switch (*flags) {
       case 'S': ...
       case 'U': ...
       default:
           .... // NOW WHAT?
       }
    }

You can't express it. Sure you can get around it, but that is just 
pandering to the issue, and it means you can't use what might be the 
most natural and clearest way to do it.

In my language and in my programs, breaking out of a loop from within a 
multi-way case/switch selection is a very, very common idiom which is 
denied to C users.
Re: Taming The Switch-Statement
#264
Author: David Brown
Date: Mon, 12 Oct 2026 14:12
149 lines
7322 bytes
On 12/10/2026 15:37, bart wrote:
> On 12/10/2026 06:05, David Brown wrote:
>> On 11/10/2026 19:57, bart wrote:
>>> On 11/10/2026 18:17, David Brown wrote:
>>
>>>> Only Michael can, if he wants, explain what he was thinking.
>>>
>>> It sounds like he's pressurised into doing so. Maybe so that he can 
>>> be lectured on how to it 'properly'.
>>
>> The "pressure" is just because people are curious for more detail. 
>> Michael is an experienced C programmer, but we all work in slightly 
>> different ways on slightly different kinds of code bases.  I can't 
>> think why breaking out of loops within switch cases would be "very 
>> common", but I have no reason to suspect Michael was not writing code 
>> "properly".   I can't think why such code - common or not - would be 
>> problematic, or why having two different "break" keywords or 
>> constructs would be better for his code.  That's why I would like 
>> Michael to give more details - not to tell him his "wrong", but to 
>> learn more about his coding.
>>
>>>
>>> 'break' to quit a loop early is part of the language, so why 
>>> shouldn't someone make use it?
>>
>> I think most C programmers do, at least occasionally.
>>
>>>
>>> It just its use can be interfered with when 'switch' is involved.
>>>
>>
>> I personally have never found an issue there.  "break" breaks out of 
>> the innermost loop or switch.  If you write switch statements that are 
>> intermingled with loops in a non-structured manner, I am sure things 
>> get difficult and unclear.  Since I do not write code with such 
>> intermingling, I have not had any such problems.
> 
> What do mean by 'intermingled' - nested? That's how structured 
> programming works!
> 

No - if I had meant "nested", I would have written "nested".  In C, 
switch statements are not fully structured.  That's why I wrote 
"intermingled".  I had assumed the meaning was clear, but there is no 
standard definition of "intermingled" code.

You can write things like :

int foo(int x) {
     int y = x;
     switch (x) {
         case 0 :
             y++;
             break;
         case 1 :
             for (y = 0; y < x; y++) {
         case 2:
                 x++;
             }
     }
     return y;
}

That is obviously a silly, invented example.  But it is possible to jump 
into loops with an outer switch.  Such things may be of use to some 
people - just as "goto" jumping around might be of use.  It is of no 
interest to me, and I don't write code that intermingles switches and 
loops (or conditionals).  I limit my switch statements to having clear 
structure - using braces to create blocks within cases if I have local 
variables.

In the hypothetical example above, if there was a "break" after "x++;", 
it could easily be unclear to the reader if it applied to the loop, or 
to the switch.  Having separate "break_switch" and "break_for" keywords 
or constructs would make that difference clear - but I cannot think of a 
real example where it would not be clearer to have the entire loop 
within one case and avoid the issue altogether.

> Otherwise there is no intermingling in this example:
> 
>      for (i=0; i < N; ++i) {
>          x = A[i];
>          if (x == 5 || x == 6 || x == 10 || x == 11) break;
> 
>          switch (A[i]) {
>          case 5: case 6: case 10: case 11: break;   // ??
>          }
>      }

That is not "intermingling", as I used the word - it is just a switch 
nested inside a loop.

> 
> The loop body shows two ways of aborting the loop when an exit condition 
> is detected:
> 
> * Using an if-statement and 'break'
> 
> * Using a switch-statement and ... break?
> 
> The second doesn't work because 'break' now shadows its outer meaning. 
> Both would otherwise be reasonable choices for this logic.

No, they would not be reasonable choices.  It is very, /very/ simple, as 
long as your code is written in a structured manner - nesting the 
constructs as you did above.  "break" applies to the innermost loop or 
switch.  That's the rule.

> 
> Here's another example:
> 
>      for (i=0; i < N; ++i) {
>          if (A[i] == 1)
>              if (!f()) break;
>          else if (A[i] == 2)
>              if (!g()) break;
>          else
>              if (!h()) break;
>      }
> 
> Here, someone might notice that 'switch' suits this pattern better than 
> an if-else chain. So they try this:
> 
>      for (i=0; i < N; ++i) {
>          switch (A[i]) {
>          case 1:
>              if (!f()) break;
>          case 2:
>              if (!g()) break;
>          default:
>              if (!h()) break;
>          }
>      }
> 
> This is valid C still, but it doesn't have the same behaviour.

Surprise!  Someone changed the code, and the behaviour changed!  Who 
could have imagined that might happen?

> In my language and in my programs,

No one else cares.  Your language is your own, and not relevant outside 
of your bubble.  You keep thinking it somehow "proves" your points, or 
that it shows how "wrong" C is - it does not.  There is no need to waste 
your time or other readers' time by writing about it.  Stick to writing 
about C here.


Re: Taming The Switch-Statement
#265
Author: David Brown
Date: Mon, 12 Oct 2026 14:15
31 lines
2982 bytes
On 12/10/2026 12:42, bart wrote:
> On 12/10/2026 06:22, David Brown wrote:
>> On 12/10/2026 00:05, bart wrote:
> 
>>> So you don't really get it. That's fine.
>>>
>>
>> So now you can drop it, along with all your other complaints about the 
>> C language and tools people use with it?
> 
> My opinions haven't changed at all. KT doesn't care because he doesn't 
> understand the importance of having properly designed features. Probably 
> he hasn't been involved in having to process somebody else's source code 
> or having to translate it or port it.
> 

Again, I am not responsible for other people's posts - but I am entirely 
confident that Keith appreciates well-designed programming languages. 
And I am entirely confident that he was a lot of experience dealing with 
other people's code.

> 
>> Alternatively, you are free to write proposals for the C standards 
>> committee, or take part in their discussions, aiming to actually 
>> change the things you so passionately insist need fixing.
> I'll be long dead before anything happens. It's taken most of my 
> lifetime before even a no-brainer like binary literals became official.

That is perhaps because the people involved with the C language not only 
/have/ brains, but they also use them.
Re: Taming The Switch-Statement
#266
Author: Scott Lurndal
Date: Mon, 12 Oct 2026 14:34
16 lines
1743 bytes
bart <bc@freeuk.com> writes:
>On 12/10/2026 06:22, David Brown wrote:
>> On 12/10/2026 00:05, bart wrote:
>
>>> So you don't really get it. That's fine.
>>>
>> 
>> So now you can drop it, along with all your other complaints about the C 
>> language and tools people use with it?
>
>My opinions haven't changed at all. KT doesn't care because he doesn't 
>understand the importance of having properly designed features.

"properly designed" by what criteria?

Making you happy is not a valid criteria.
Re: Taming The Switch-Statement
#267
Author: bart
Date: Mon, 12 Oct 2026 15:32
90 lines
5140 bytes
On 12/10/2026 15:12, David Brown wrote:
> On 12/10/2026 15:37, bart wrote:

> That is obviously a silly, invented example.

Yes, but I am not discussing that in this post. The subthread is 
switch-break interfering with loop-break.


>>
>> The loop body shows two ways of aborting the loop when an exit 
>> condition is detected:
>>
>> * Using an if-statement and 'break'
>>
>> * Using a switch-statement and ... break?
>>
>> The second doesn't work because 'break' now shadows its outer meaning. 
>> Both would otherwise be reasonable choices for this logic.
> 
> No, they would not be reasonable choices.

Why not? You seem to be talking about both IF and SWITCH here; are there 
any other conditional control-flow statements that I'm not aware of?

Or is your more reasonable approach involving superfluous loops or 
superfluous functions (just to score some point)?

We're trying to avoid convoluted code.

>  It is very, /very/ simple, as 
> long as your code is written in a structured manner - nesting the 
> constructs as you did above.  "break" applies to the innermost loop or 
> switch.  That's the rule.

Yes, we know that's rule! And that is the problem: the break of switch 
interferes with normal loop break, which means that forces your hand 
whenever you'd prefer to use the more apt 'switch' construct.

>> This is valid C still, but it doesn't have the same behaviour.
> 
> Surprise!  Someone changed the code, and the behaviour changed!  Who 
> could have imagined that might happen?

Now you're being facetious. THE BEHAVIOUR SHOULD BE EXACTLY THE SAME:

     Loop
        ....
        Break when some condition is true
        ....

You should be able to choose how you write your conditions. So the fact 
that the behaviour changes while expressing the same logic IS THE PROBLEM.

I mean, why on earth should it? Just because some numskull decided to 
use the same fucking keyword for two different things?

Now, everyone is trying to suggest it was in fact a wonderful idea, you 
save one whole keyword, and that it's SO easy to try and avoid the 
ensuing mess by programming your way around it or avoiding certain 
statement combos.


>> In my language and in my programs,
> 
> No one else cares.  Your language is your own, and not relevant outside 
> of your bubble.  You keep thinking it somehow "proves" your points, or 
> that it shows how "wrong" C is - it does not.

Then you've just got your head in the sand, sorry.

People have been asking about examples of exiting a loop from within 
switch, and in my code there are myriad such examples, even more than 
I'd thought (I guess I don't even think about it).

That they're in a different language doesn't matter: it shows the idiom, 
that code-pattern, can be useful and can be the more natural and 
intuitive choice.

Of course you won't find such examples in C because the language doesn't 
allow it!

Oh, and I also showed an easy solution to the nested loops issue.


>  There is no need to waste 
> your time or other readers' time by writing about it.  Stick to writing 
> about C here.
The subject is Taming the Switch-Statement, and the opening post was 
ways to forget writing that famous 'break'.
Re: Taming The Switch-Statement
#269
Author: bart
Date: Mon, 12 Oct 2026 15:47
34 lines
2794 bytes
On 12/10/2026 15:34, Scott Lurndal wrote:
> bart <bc@freeuk.com> writes:
>> On 12/10/2026 06:22, David Brown wrote:
>>> On 12/10/2026 00:05, bart wrote:
>>
>>>> So you don't really get it. That's fine.
>>>>
>>>
>>> So now you can drop it, along with all your other complaints about the C
>>> language and tools people use with it?
>>
>> My opinions haven't changed at all. KT doesn't care because he doesn't
>> understand the importance of having properly designed features.
> 
> "properly designed" by what criteria?
> 
> Making you happy is not a valid criteria.

Is there any language that you would consider badly designed?

If so, what would you do if it become amazingly popular and you were 
obliged to deal with it in your work; would you change your mind, or 
would you still think it was poor?

Hopefully the latter.

But back to C: this is how 'switch' is defined in the grammar:

   'switch' ( expression ) statement

Notice no mention of 'case' or 'default' statements!

Is that not a giant red flag, that there is normal shape to 
switch-statement syntax?
Re: Taming The Switch-Statement
#270
Author: Johann 'Myrkraverk' Oskarsson
Date: Mon, 12 Oct 2026 16:15
50 lines
3182 bytes
On 10/12/2026 11:47 PM, bart wrote:
> On 12/10/2026 15:34, Scott Lurndal wrote:
>> bart <bc@freeuk.com> writes:
>>> On 12/10/2026 06:22, David Brown wrote:
>>>> On 12/10/2026 00:05, bart wrote:
>>>
>>>>> So you don't really get it. That's fine.
>>>>>
>>>>
>>>> So now you can drop it, along with all your other complaints about 
>>>> the C
>>>> language and tools people use with it?
>>>
>>> My opinions haven't changed at all. KT doesn't care because he doesn't
>>> understand the importance of having properly designed features.
>>
>> "properly designed" by what criteria?
>>
>> Making you happy is not a valid criteria.
> 
> Is there any language that you would consider badly designed?
> 
> If so, what would you do if it become amazingly popular and you were 
> obliged to deal with it in your work; would you change your mind, or 
> would you still think it was poor?
> 
> Hopefully the latter.
> 
> But back to C: this is how 'switch' is defined in the grammar:
> 
>    'switch' ( expression ) statement
> 
> Notice no mention of 'case' or 'default' statements!
> 
> Is that not a giant red flag, that there is normal shape to switch- 
> statement syntax?

Not to me.  A giant red flag would be something akin to

   switch ( foo ) printf( "Hello, bart\n" ) ;

where the printf() never gets called.


Best wishes, and happy red flags!
-- 
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
#271
Author: Stefan Ram
Date: Mon, 12 Oct 2026 17:02
15 lines
2522 bytes
Johann 'Myrkraverk' Oskarsson <johann@myrkraverk.invalid> wrote or quoted:
>Not to me.  A giant red flag would be something akin to
>   switch ( foo ) printf( "Hello, bart\n" ) ;
>where the printf() never gets called.

  GCC also flags it:

main.c: In function 'main':
main.c:3:30: warning: statement will never be executed [-Wswitch-unreachable]
    3 | int main( void ){ switch( 0 )printf( "Hello!\n" ); }
      |                              ^~~~~~~~~~~~~~~~~~~~

  . I use, " . . . -pedantic . . . -Wall -W -Wextra -Wpedantic . . .".

Re: Taming The Switch-Statement
#272
Author: David Brown
Date: Mon, 12 Oct 2026 17:05
149 lines
7804 bytes
On 12/10/2026 17:32, bart wrote:
> On 12/10/2026 15:12, David Brown wrote:
>> On 12/10/2026 15:37, bart wrote:
> 
>> That is obviously a silly, invented example.
> 
> Yes, but I am not discussing that in this post. The subthread is switch- 
> break interfering with loop-break.
> 

"Switch break" does not in any sense interfere with "loop break".  There 
is no interference, no conflict, no confusion.  "break" leaves the 
current innermost switch or loop.  It is simple and obvious.  And while 
I agree that occasionally you might want a want to break out of an outer 
switch or loop from within an inner one, it applies equally to two 
nested loops, two nested switches, a switch containing a nested loop, 
and a loop containing a nested switch.

> 
>>>
>>> The loop body shows two ways of aborting the loop when an exit 
>>> condition is detected:
>>>
>>> * Using an if-statement and 'break'
>>>
>>> * Using a switch-statement and ... break?
>>>
>>> The second doesn't work because 'break' now shadows its outer 
>>> meaning. Both would otherwise be reasonable choices for this logic.
>>
>> No, they would not be reasonable choices.
> 
> Why not? You seem to be talking about both IF and SWITCH here; are there 
> any other conditional control-flow statements that I'm not aware of?

I am sure you have read the C standards, so that you know the answer to 
that.

> 
> Or is your more reasonable approach involving superfluous loops or 
> superfluous functions (just to score some point)?
> 
> We're trying to avoid convoluted code.
> 

No, I don't think "we" are trying to do anything.  /You/ are trying to 
invent problems, and to persuade others that the confusions in your own 
mind are real issues for C programmers.  I am explaining that there is 
no special challenge here.

>>   It is very, /very/ simple, as long as your code is written in a 
>> structured manner - nesting the constructs as you did above.  "break" 
>> applies to the innermost loop or switch.  That's the rule.
> 
> Yes, we know that's rule! 

So we are done, then?  One simple rule to learn - and a pretty obvious 
rule at that.  Now you know the answer, you can stop worrying about it.

> And that is the problem: the break of switch 
> interferes with normal loop break, which means that forces your hand 
> whenever you'd prefer to use the more apt 'switch' construct.

There is no interference.  There is a /limitation/ - "break" only exits 
the innermost structure, and cannot break out of outer structures.  It's 
like "return" only returns from the current function, not the function 
that called it.

> 
>>> This is valid C still, but it doesn't have the same behaviour.
>>
>> Surprise!  Someone changed the code, and the behaviour changed!  Who 
>> could have imagined that might happen?
> 
> Now you're being facetious. THE BEHAVIOUR SHOULD BE EXACTLY THE SAME:
> 

Only in your mind.

You changed the code significantly, and the behaviour changes.

>      Loop
>         ....
>         Break when some condition is true
>         ....
> 
> You should be able to choose how you write your conditions. So the fact 
> that the behaviour changes while expressing the same logic IS THE PROBLEM.

You can often express the same logic in many different ways in code, and 
the details of how you write the code need to be changed to match.  Why 
should anyone expect that an "if" statement can be changed to a "switch" 
statement and everything else should remain the same?  If I change a 
"while" loop to a "do" loop, it's still a loop - but the contents must 
be changed if I want the same behaviour.

You are inventing things that don't exist outside your imagination, and 
then complaining that C was not designed specifically to suit the rules 
you just made up.

> 
> I mean, why on earth should it? Just because some numskull decided to 
> use the same fucking keyword for two different things?
> 
> Now, everyone is trying to suggest it was in fact a wonderful idea, you 
> save one whole keyword, and that it's SO easy to try and avoid the 
> ensuing mess by programming your way around it or avoiding certain 
> statement combos.
> 

Again, I can't speak for anyone else.  But the very idea that any of 
this should be difficult or an issue for any normal (not psychotic) C 
programmer had never occurred to me until it was brought up in this thread.

> 
>>> In my language and in my programs,
>>
>> No one else cares.  Your language is your own, and not relevant 
>> outside of your bubble.  You keep thinking it somehow "proves" your 
>> points, or that it shows how "wrong" C is - it does not.
> 
> Then you've just got your head in the sand, sorry.
> 
> People have been asking about examples of exiting a loop from within 
> switch, and in my code there are myriad such examples, even more than 
> I'd thought (I guess I don't even think about it).
> 
> That they're in a different language doesn't matter: it shows the idiom, 
> that code-pattern, can be useful and can be the more natural and 
> intuitive choice.
> 
> Of course you won't find such examples in C because the language doesn't 
> allow it!
> 
> Oh, and I also showed an easy solution to the nested loops issue.
> 
> 
>>   There is no need to waste your time or other readers' time by 
>> writing about it.  Stick to writing about C here.
> The subject is Taming the Switch-Statement, and the opening post was 
> ways to forget writing that famous 'break'.

We all know that some people sometimes forget "break" statements in 
their switches.  Mistakes and typos happen to the best of us, in all 
programming languages, and every programming language has its own 
selection of "archetypical" mistakes, and tools to help catch or avoid them.


Re: Taming The Switch-Statement
#273
Author: Scott Lurndal
Date: Mon, 12 Oct 2026 17:17
31 lines
2394 bytes
bart <bc@freeuk.com> writes:
>On 12/10/2026 15:34, Scott Lurndal wrote:
>> bart <bc@freeuk.com> writes:
>>> On 12/10/2026 06:22, David Brown wrote:
>>>> On 12/10/2026 00:05, bart wrote:
>>>
>>>>> So you don't really get it. That's fine.
>>>>>
>>>>
>>>> So now you can drop it, along with all your other complaints about the C
>>>> language and tools people use with it?
>>>
>>> My opinions haven't changed at all. KT doesn't care because he doesn't
>>> understand the importance of having properly designed features.
>> 
>> "properly designed" by what criteria?
>> 
>> Making you happy is not a valid criteria.
>
>Is there any language that you would consider badly designed?

I would prefer that you first describe the specific generic
criteria that you believe apply to a "properly designed" language,
rather than attempting to change the topic, and then explicitly
noting which of those generic criteria are violated by early
exits from switch statements in the C language which is the
nominal topic for this usenet newsgroup.

Please do not reference your personal languages, compilers or
opinions.
Re: Taming The Switch-Statement
#274
Author: Dan Cross
Date: Mon, 12 Oct 2026 17:34
73 lines
4215 bytes
In article <11aidi3$3gbu4$1@dont-email.me>, bart  <bc@freeuk.com> wrote:
>On 12/10/2026 06:22, David Brown wrote:
>> On 12/10/2026 00:05, bart wrote:
>
>>> So you don't really get it. That's fine.
>>>
>> 
>> So now you can drop it, along with all your other complaints about the C 
>> language and tools people use with it?
>
>My opinions haven't changed at all. KT doesn't care because he doesn't 
>understand the importance of having properly designed features. Probably 
>he hasn't been involved in having to process somebody else's source code 
>or having to translate it or port it.

I think you're free to criticize the language, if you like.  But
you are not free to assign to others opinions that they may not
hold; at least if you intend to be taken seriously.

I kinda sorta agree that requiring `break` between `case`
statements in C was an historical mistake, but here we are: it
is 2026, and the language has done that for more than 50 years
now.  The ship for changing it has sailed.  What is one left to
do, besides acknowledging it as a wart on the face of the
langauge?

Everyone here knows that C is imperfect; everyone knows that if
one were starting from scratch now, given the hindsight of 50+
years, one would do things differently.  So what?  We're not
starting from scratch, the language we have is the language that
we have, and there are real-world complexities that make it
difficult (at best!) to change.  Simply put, no one is
suggesting that C is perfect, but people are saying that one can
live with it.

I don't read Keith trying to defend C here so much as simply
explain what it does, and how one works around the complaints
about it that you identify.

>I have an old tool which /visualises/ C source code by trying to express 
>it in my syntax. It is not a formal transpiler: the semantics are not 
>translated, just the shape of the code.
>
>Still, the transformation is usually startlingly clear compared with the 
>original. Anyway I applied it to two examples, first:
>
>[snip]

So what?  What do you think that that shows?  That your language
doesn't have `break`?  Ok, but you already knew that, right?  We
have it on your authority that it is true, so we know that, too.
But why does it matter?

I find such arguments strange, as they're not really arguing
anything meaningful.  It's like Anton Ertl's complaint about
Rust vis binary search trees in `comp.arch`: because he did
not write his tree implementation using completely safe Rust
_the same way he did in C_, then somehow Rust is deficient; but
Rust is a different programming language, with different
semantics and different constraints about how objects may be
referred to, etc.  That the structure of a program in two
different programming languages with different semantics is
different seems axiomatic, and frankly doesn't say much about
the language.  So it is here, as well.

You can fairly say, "I don't like this" about something in C;
that's fine.  Others may even agree with you.  But C is what it
is, and unless you're willing to engage with the committee and
larger language community to change it (which is going to be
very, very hard; buckle up) then that is all that it will be.

	- Dan C.
Re: Taming The Switch-Statement
#275
Author: Dan Cross
Date: Mon, 12 Oct 2026 17:37
33 lines
2076 bytes
In article <11aivdn$3nvmh$1@dont-email.me>, bart  <bc@freeuk.com> wrote:
>On 12/10/2026 15:34, Scott Lurndal wrote:
>> bart <bc@freeuk.com> writes:
>>> On 12/10/2026 06:22, David Brown wrote:
>>>> On 12/10/2026 00:05, bart wrote:
>>>
>>>>> So you don't really get it. That's fine.
>>>>>
>>>>
>>>> So now you can drop it, along with all your other complaints about the C
>>>> language and tools people use with it?
>>>
>>> My opinions haven't changed at all. KT doesn't care because he doesn't
>>> understand the importance of having properly designed features.
>> 
>> "properly designed" by what criteria?
>> 
>> Making you happy is not a valid criteria.
>
>Is there any language that you would consider badly designed?

Yes.  PHP.

>If so, what would you do if it become amazingly popular and you were 
>obliged to deal with it in your work; would you change your mind, or 
>would you still think it was poor?

Fortunately, I am not obliged to deal with PHP, but if I were, I
suspect my opinion of it would go down, not up.  Regardless, I
think it fair to categorize it as, "amazingly popular."

	- Dan C.
Re: Taming The Switch-Statement
#276
Author: Dan Cross
Date: Mon, 12 Oct 2026 17:58
187 lines
7006 bytes
In article <11ainqf$3kkvd$1@dont-email.me>, bart  <bc@freeuk.com> wrote:
>On 12/10/2026 06:05, David Brown wrote:
>> On 11/10/2026 19:57, bart wrote:
>>> On 11/10/2026 18:17, David Brown wrote:
>> 
>>>> Only Michael can, if he wants, explain what he was thinking.
>>>
>>> It sounds like he's pressurised into doing so. Maybe so that he can be 
>>> lectured on how to it 'properly'.
>> 
>> The "pressure" is just because people are curious for more detail. 
>> Michael is an experienced C programmer, but we all work in slightly 
>> different ways on slightly different kinds of code bases.  I can't think 
>> why breaking out of loops within switch cases would be "very common", 
>> but I have no reason to suspect Michael was not writing code "properly". 
>>   I can't think why such code - common or not - would be problematic, or 
>> why having two different "break" keywords or constructs would be better 
>> for his code.  That's why I would like Michael to give more details - 
>> not to tell him his "wrong", but to learn more about his coding.
>> 
>>>
>>> 'break' to quit a loop early is part of the language, so why shouldn't 
>>> someone make use it?
>> 
>> I think most C programmers do, at least occasionally.
>> 
>>>
>>> It just its use can be interfered with when 'switch' is involved.
>>>
>> 
>> I personally have never found an issue there.  "break" breaks out of the 
>> innermost loop or switch.  If you write switch statements that are 
>> intermingled with loops in a non-structured manner, I am sure things get 
>> difficult and unclear.  Since I do not write code with such 
>> intermingling, I have not had any such problems.
>
>What do mean by 'intermingled' - nested? That's how structured 
>programming works!

Keith explained this already, but I feel obligated to respond to
a point....

>Otherwise there is no intermingling in this example:
>
>     for (i=0; i < N; ++i) {
>         x = A[i];
>         if (x == 5 || x == 6 || x == 10 || x == 11) break;
>
>         switch (A[i]) {
>         case 5: case 6: case 10: case 11: break;   // ??
>         }
>     }

    for (i = 0; i < N; i++) {
        x = A[i];
        switch (x) {
        case 5: case 6: case 10: case 11: goto out;
        }
    }
out:

>The loop body shows two ways of aborting the loop when an exit condition 
>is detected:
>
>* Using an if-statement and 'break'
>
>* Using a switch-statement and ... break?

Goto.

"If you want to go somewhere, goto is the best way to get
there." -- Ken Thompson, via the Plan 9 `fortune` file.

Alternatively, one might extract the loop into its own little
function, and use an early `return` to break out of it:

	static inline void
	loop(void)
	{

		for (i = 0; i < N; i++) {
			x = a[i];
			switch (x) {
			case 5: case 6: case 10: case 11: return;
			}
			// Do whatever here.
		}
	}

...and back in the caller:

	loop();

>The second doesn't work because 'break' now shadows its outer meaning. 
>Both would otherwise be reasonable choices for this logic.
>
>Here's another example:
>
>     for (i=0; i < N; ++i) {
>         if (A[i] == 1)
>             if (!f()) break;
>         else if (A[i] == 2)
>             if (!g()) break;
>         else
>             if (!h()) break;
>     }
>
>Here, someone might notice that 'switch' suits this pattern better than 
>an if-else chain. So they try this:
>
>     for (i=0; i < N; ++i) {
>         switch (A[i]) {
>         case 1:
>             if (!f()) break;
>         case 2:
>             if (!g()) break;
>         default:
>             if (!h()) break;
>         }
>     }

```
	for (i = 0; i < N; i++) {
		switch (A[i]) {
		case 1: if (!f()) goto out;
		case 2: if (!g()) goto out;
		default: if (!h()) goto out;
		}
	}
out:
```

>This is valid C still, but it doesn't have the same behaviour.

Yes.  I guess I fail to see the point of these, as what you are
trying to show seems obvious to me, and I strongly suspect it is
obvious to others, as well.

Are you suggesting that people are unaware of how `break`
interacts with `switch` inside of a loop?  I don't think that is
true; I think people are well aware, but know how to work around
it and don't see it as a huge impediment; more of a mild
inconvenience.

Or are you suggesting that they are trying to defend the design
of the language in this regard?  I similarly don't think that is
true; I have certainly been annoyed by this, and I suspect
others have as well.  But again, people know how to work around
it.

C is not anyone's mother; I doubt anyone who is not a kook feels
like they need to rise to the defense of its honor when it is
criticized.

What I think some people are sort of mystified by is this idea
that this one thing is such a deal-breaker as to render the
language unuseable.  That is certainly not true; whatever its
deficiencies, C has become fundamental to the working of the
modern world, and one avails oneself of considerable networking
effects if one uses it.

>Maybe, some compilers with certain options may point out something about 
>fall-through, so you're aware something's amiss, but it doesn't get 
>around the problem: you can't simply swap if-else chains with switch 
>even when the latter is a better fit.
>
>This is a definite flaw in the language.

It _can be_ an _annoyance_ in the language, sure.  Is it a,
"definite flaw"?  That is subjective.  You clearly feel that it
is.  I couldn't say whether anyone else feels that way; I think
it's too minor to matter for most programmers.

>[snip]
>In my language and in my programs, breaking out of a loop from within a 
>multi-way case/switch selection is a very, very common idiom which is 
>denied to C users.

And yet, C is used successfully by millions of programmers
around the world, the results of which are used by billions of
users daily.

So is it flawed?  By the designer's own account, yes.  Is it
workable?  Obviously.

	- Dan C.
Re: Taming The Switch-Statement
#277
Author: bart
Date: Mon, 12 Oct 2026 18:15
66 lines
4195 bytes
On 12/10/2026 18:05, David Brown wrote:
> On 12/10/2026 17:32, bart wrote:

>>>> The loop body shows two ways of aborting the loop when an exit 
>>>> condition is detected:
>>>>
>>>> * Using an if-statement and 'break'
>>>>
>>>> * Using a switch-statement and ... break?
>>>>
>>>> The second doesn't work because 'break' now shadows its outer 
>>>> meaning. Both would otherwise be reasonable choices for this logic.
>>>
>>> No, they would not be reasonable choices.
>>
>> Why not? You seem to be talking about both IF and SWITCH here; are 
>> there any other conditional control-flow statements that I'm not aware 
>> of?
> 
> I am sure you have read the C standards, so that you know the answer to 
> that.

I still don't know what you mean. So, using 'if' for conditional exit 
from a loop is unreasonable. But so is 'switch', even putting aside the 
issue with break.

It seems to me that you are just gaslighting now.

>> Yes, we know that's rule! 
> 
> So we are done, then?  One simple rule to learn - and a pretty obvious 
> rule at that.  Now you know the answer, you can stop worrying about it.

What? Having a stupid rule in place doesn't mean it hasn't caused issues!


>> And that is the problem: the break of switch interferes with normal 
>> loop break, which means that forces your hand whenever you'd prefer to 
>> use the more apt 'switch' construct.
> 
> There is no interference.  There is a /limitation/ - "break" only exits 
> the innermost structure, and cannot break out of outer structures.  It's 
> like "return" only returns from the current function, not the function 
> that called it.

It's a good thing that they didn't choose to use 'return' for both loop 
exit and switch-break then!

But if they had:

* You couldn't use early return from inside a loop

* Nor from inside a switch

* You still couldn't exit early from a loop from inside switch

* 'return' would do three different things depending on context,
   but none interfere with each other

Obviously this wouldn't be a problem for you either? After all that 
would be the rule, still a fairly simple one. And it would have saved 
one more keyword which is really, really important.

Yeah, I think now we're done.

Re: Taming The Switch-Statement
#279
Author: Scott Lurndal
Date: Mon, 12 Oct 2026 18:46
24 lines
2017 bytes
cross@spitfire.i.gajendra.net (Dan Cross) writes:
>In article <11aidi3$3gbu4$1@dont-email.me>, bart  <bc@freeuk.com> wrote:
>>On 12/10/2026 06:22, David Brown wrote:
>>> On 12/10/2026 00:05, bart wrote:
>>

>I kinda sorta agree that requiring `break` between `case`
>statements in C was an historical mistake, but here we are: it
>is 2026, and the language has done that for more than 50 years
>now.  The ship for changing it has sailed.  What is one left to
>do, besides acknowledging it as a wart on the face of the
>langauge?

I, on the other hand, don't consider it a mistake, in the
context of the C and C++ languages.   I've used the ability to
fall through in a significant fraction (50% in some applications) of
the switch statements that I've written over the last
five decades of C  and C++programming.

Absent other changes to the syntax (e.g. non-contiguous ranges
in the case selector[*]) the requirement to use break to avoid
falling through to other cases is rather valuable to me.

[*] I also use the gcc extension supporting contiguous ranges heavily.
Page 2 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