Thread View: comp.lang.c
412 messages
412 total messages
Page 7 of 9
Started by Lawrence D’Oliveiro
Sat, 10 Oct 2026 00:25
Page 7 of 9 • 412 total messages
Re: Taming The Switch-Statement
Author: Bob Duff
Date: Mon, 19 Oct 2026 23:38
Date: Mon, 19 Oct 2026 23:38
40 lines
2914 bytes
2914 bytes
Keith Thompson <Keith.S.Thompson+u@gmail.com> writes:
> Names used for loops have a lighter-weight syntax:
>
> LOOP_NAME:
> while condition loop
> -- ...
> end loop;
That's a syntax error. In Ada, if you put a loop name at the top of the
loop, you are required to repeat it at the bottom, like this:
LOOP_NAME: while condition loop
...
end loop LOOP_NAME;
If there's an "exit LOOP_NAME;" in there, it's pretty clear which
loop it's jumping out of, AND where it's jumping to.
> I can't think of a better syntax for loop names than "NAME:" (used
> by several other languages), but in C that syntax is already
> taken for goto labels.
Agreed.
But in current C (before adding the named-loop feature),
and in Ada, and in many other languages, a label serves
as a warning: One or more gotos jump here. That's useful
information.
This new feature of C seems to lose that benefit, which
is unfortunate. But I think the "while LOOP_NAME..."
syntax is less readable than "LOOP_NAME: while...",
as you said.
So if it were up to me, I wouldn't add named loops to C in
either proposed syntax. The "goto" is good enough for
jumping out of nested loops.
- Bob
Re: Taming The Switch-Statement
Author: Kaz Kylheku
Date: Mon, 19 Oct 2026 23:41
Date: Mon, 19 Oct 2026 23:41
67 lines
4685 bytes
4685 bytes
On 2026-10-16, Keith Thompson <Keith.S.Thompson+u@gmail.com> wrote:
> Tim Rentsch <tr.17687@z991.linuxsc.com> writes:
>> Keith Thompson <Keith.S.Thompson+u@gmail.com> writes:
>>> I find "break NAME;", where "NAME" is the name of an enclosing
>>> construct, unambiguously better than "break N;", where N is the
>>> number of levels to break out of. [...]
>>
>> Definitely.
>>
>>> There's a proposal for C2y to use goto labels as loop names, and a
>>> competing one to define a new syntax like "for NAME (;;)" :
>>>
>>> https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3355.htm
>>> https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3377.pdf
>>
>> I'm not particularly a fan of multi-level break/continue. But if
>> we're going to have one of these, the second ("for NAME (;;)") is
>> unquestionably better.
>
> Unquestionably? Why?
>
> I do like the fact that it doesn't conflate goto labels with loop
> names, but I still prefer the "NAME: for (;;)" form, partly because
> it's consistent with several other languages.
If a loop has a statement label, traditionally usable with goto,
and we allow it to be used with a break, that is still a "goto label".
The break is a kind of goto, and the named break is a goto-like transfer
whose target is found with the help of the label, just a little
differently from goto. It goes past the labeled statement, essentially.
It's a "goto-adjacent operation" or "close sibling of goto".
It could be generalized such that if there is a labelled statement
"L: S" in the function scope, then "break X" anywhere in the function
can be used anywhere in the function to jump to that abstract point
where control ends up immediately after the execution of S.
In other words, supposed things were as if L: S had the meaning
L: { S; __L_after :; } and "break L;" with a label argument then
has the meaning "goto __L_after". Except that there is no such
code transformation; the target of "break L" is an abstract point
relatie to the statement labeleld by L without any invisible
auxilirary derived label.
Then there would be complete consistency: the scope of L would be
the same regardless of whether it is used as a break or goto target,
and L would be acting as a control transfer destination in both
uses, disparaging all traces of a conflation.
Now imagine that we have this design and we don't like that
a break can transfer past a labelled statement from anywhere
in a function.
We can then add the constraint that a "break L" statement is
required to be located inside the statement labelled by L.
That does not change the scope; it's just a constraint. A "break L"
outside of that statement is understood perfectly well as referring to
unambiguously that L, but required to be diagnosed. (Could be readily
supported as an extension.)
--
TXR Programming Language: http://nongnu.org/txr
Cygnal: Cygwin Native Application Library: http://kylheku.com/cygnal
Mastodon: @Kazinator@mstdn.ca
Re: Taming The Switch-Statement
Author: Keith Thompson
Date: Tue, 20 Oct 2026 00:03
Date: Tue, 20 Oct 2026 00:03
66 lines
4393 bytes
4393 bytes
Bob Duff <invalid@invalid.com> writes:
> Keith Thompson <Keith.S.Thompson+u@gmail.com> writes:
>> Names used for loops have a lighter-weight syntax:
>>
>> LOOP_NAME:
>> while condition loop
>> -- ...
>> end loop;
>
> That's a syntax error. In Ada, if you put a loop name at the top of the
> loop, you are required to repeat it at the bottom, like this:
>
> LOOP_NAME: while condition loop
> ...
> end loop LOOP_NAME;
Right, I forgot that. It's also a syntax error because there are no
statements in the body of the loop, just a comment.
> If there's an "exit LOOP_NAME;" in there, it's pretty clear which
> loop it's jumping out of, AND where it's jumping to.
Yes.
>> I can't think of a better syntax for loop names than "NAME:" (used
>> by several other languages), but in C that syntax is already
>> taken for goto labels.
>
> Agreed.
>
> But in current C (before adding the named-loop feature),
> and in Ada, and in many other languages, a label serves
> as a warning: One or more gotos jump here. That's useful
> information.
Well, zero or more gotos, but yes.
> This new feature of C seems to lose that benefit, which
> is unfortunate. But I think the "while LOOP_NAME..."
> syntax is less readable than "LOOP_NAME: while...",
> as you said.
Agreed -- but you can always search a function body for occurrences
of "goto". If a function is big enough to make that difficult,
either it's machine-generated or you should probably rethink your
program structure.
Once the new feature is widely available, I think that the fact that
a label is at the top of a loop or switch statement is a strong clue
that it's *not* the target of a goto.
> So if it were up to me, I wouldn't add named loops to C in
> either proposed syntax. The "goto" is good enough for
> jumping out of nested loops.
I commonly use named loops in Perl -- and in a recent search through
a bunch of my Perl code, I found that I typically *don't* use it as
a way to break out of a nested loop. I find that giving a name to a
loop can make the code easier to understand: this loop iterates over
command-line arguments, that one iterates over lines in a file. (Perl
uses the same syntax for goto labels and loop names. I don't think
I've ever used goto in Perl outside small throwaway test scripts.)
--
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
Author: Waldek Hebisch
Date: Tue, 20 Oct 2026 00:16
Date: Tue, 20 Oct 2026 00:16
104 lines
6336 bytes
6336 bytes
Tim Rentsch <tr.17687@z991.linuxsc.com> wrote:
> antispam@fricas.org (Waldek Hebisch) writes:
>
>> Lawrence D?Oliveiro <ldo@nz.invalid> wrote:
>>
>>> On Tue, 13 Oct 2026 07:23:40 -0000 (UTC), Waldek Hebisch wrote:
>>>
>>>> So what those counts indicate: majority of loops is simple, that is
>>>> have no early exit. Vast majority of early exits is done via
>>>> 'return'.
>>>
>>> My experience in my own C code is quite the opposite. Lots of loops
>>> have exits in the middle, leading me to use forms like ?for (;;)?. I
>>> also try to avoid putting ?return? anywhere other than the end of a
>>> function, to make it easier to see the flow of control.
>>
>> Well, usually there is a lot of loops. Those with exit in the
>> middle are still significant.
>>
>> Concernig 'return', having it in place where all work inside function
>> is done help me to see flow control and avoids complications. In
>> case of search functions it means return from the middle of the loop.
>> IMO possible alternatives like flag variables or break and retrun
>> after loop are worse.
>
> I rarely use 'break' to exit a loop. Part of this is that I try to
> write standard loops so that they complete as part of the loop test
> (i.e., in while() or for() control expressions). That isn't the
> whole story though so let me talk about 'return'.
I counted various constructs in a small suite of 2 programs (1306
lines in 3 files). There are 4 breaks outside switches and 32
loops in total. My gut feeling is that this proportion is
reasonable close to typical in my code. For comparison, there
are 67 functions and 70 'if'-s.
> Most of the functions I write have exactly one return, at the end of
> the function. I estimate this pattern accounts for around 85% of
> all functions, let's say plus or minus 5%.
In code above about half of functions is 'void' and there are 34
explicit returns (of which at least 2 are early returns).
> Sometimes functions have early returns for errors or exceptional
> conditions.
Code above contains 16 occurences of 'exit(1)'. One of those is
in a macro that is used 10 times, so actually there are 25 places
which call 'exit(1)'. That is related to the programs being
simple utilities, there is no attempt to error recovery, on error
programs simply print error message and exit.
> Early returns are easily seen to lie outside the main
> body of function processing so they don't interfere with
> understanding what the rest of the function is doing or how it
> works.
>
> A fairly common sub-pattern are functions most of whose body is a
> switch() statement, with all of the switch() cases being a simple
> return.
Code above has 2 switches, both are in parsing functions, where
cases either move to next state or signal error. Parsing functions
also open file and close it when finished and return data structure
with parsed info.
> It does sometimes happen that a function will have a loop with a
> return in the middle, and also a return at the end for what to do if
> the loop terminates. To me having an in-loop return looks better
> than using an assignment and a break.
>
> A fairly rare but important pattern is what I might call vectoring
> or decomposition. Here the function body serves to distinguish and
> separate out different regimes of subprocessing. To continue
> processing in a particular regime, a return is used not to directly
> yield a value but rather to call a further function to handle that
> sub-domain. The benefit here is both to keep function bodies small
> and to allow re-use of commonly called sub-functions.
>
> Two aspects are important for having these different styles work
> together. One is that it's easy to distinguish the different kinds
> of patterns, and by far the most simple pattern is the most common.
> The other is to be sure to keep function bodies small. Keeping
> function bodies small goes a long way in making them easy to
> understand, which obviously is a key property in writing good code.
> Also keeping function bodies small effectively prevents mixing
> different styles in a single function, serving to reinforce point
> one.
I think that in general my C code has similar characteristics. But
let me note that while I have a lot of small functions, I also have
some which are bigger. I suspect that 10% or more of my code is
in functions that are bigger then 30 lines. Such functions
frequently have several variables and there is setup stage to
initialize things, actual processing and final part (cleanups,
possibly extraction of result). Stages are clearly sepatated
by their position inside function, OTOH are strongly coupled due
to use of variables. My feeling here is that in case of strongly
coupled code with no reusable parts keeping it inside single
function is more managable than trying to split it into smaller
functions.
--
Waldek Hebisch
Re: Taming The Switch-Statement
Author: Dan Cross
Date: Tue, 20 Oct 2026 01:02
Date: Tue, 20 Oct 2026 01:02
11 lines
1273 bytes
1273 bytes
In article <86y0btofoy.fsf@linuxsc.com>,
Tim Rentsch <tr.17687@z991.linuxsc.com> wrote:
>[snip]
>Anyone who thinks my statement "the second ("for NAME (;;)") is
>unquestionably better" was meant as a statement of fact rather
>than a statement of opinion is an idiot.
Yeah? Well, that's just, like, your opinion, man.
- Dan C.
Re: Taming The Switch-Statement
Author: Waldek Hebisch
Date: Tue, 20 Oct 2026 01:03
Date: Tue, 20 Oct 2026 01:03
64 lines
3957 bytes
3957 bytes
bart <bc@freeuk.com> wrote:
>
> OK. But they HAD to create C? There were quite a few languages in the
> early 70s too: like Pascal, Fortran, PL/I, Coral-66, plus of course BCPL
> and B. So why a new one?
You ignore fact that Ritche wanted reasonably fast code from
very simple compiler. Around 1970 that meant in particular
pointer arithmetic. Also, address operator allowed simple
interfacing between pointer-oriented code and use of variables.
It is hard to imagine getting similar effect with different
semantics. IIUC C was not the only language going in this
direction, but mainstream languages were different.
Concerning specific languages, there was FORTRAN 66, it had 'do'
loop as only structured control structure, there rest of control
was via gotos. And the only data structure were array. Without
extentions FORTRAN 66 was unsuitable for system work, and arguably
for non-numeric work even early C was nicer than FORTRAN 66.
For reasonable speed FORTRAN 66 needed an optimizer which led
to compiler too big to run on a small machine.
PL/I had most needed features. But PL/I was a big language,
to run on small machine they would have to take tiny subset
and then add extentions. Basicaly they would end up with a
language which is very far from PL/I.
Similarly, BCPL was too complicated, B and C were simplifications
and adaptations small machine.
I think that Pascal was too late: nominally it was created earlier
but I think that it was available to Bell Labs only after they
did initial work leading to C. And Pascal shared problem of
speed on small machines. Note that later UCSD Pascal which
run on micros compiled to interpreted bytecode, which significantly
reduced performance.
> FORTRAN syntax looked nothing like C! Unless you mean the general
> pattern of 'INTEGER A, B' which was shared by half of all languages.
I think more pattern of
INTEGER A(20), B
which has similar structure to C variable declarations. Of course,
FORTRAN had no pointers (and structures or unions), so Ritche had
to invent syntax for them.
IMO C suffers because typedef was added late in the game and
function prototypes are much later. Prototypes need types and
to get it one needs "hole" in variable declaration. Where the
hole should be is specified by the C syntax, but placement of
hole is probably least clear aspect of declarations.
IMO C declaration syntax was a mistake, but as real life shows
it was not a fatal mistake, people can adapt. Note that in
eighties C position among system languages was not as strong as
it is now. In particular there were quite decent Modula 2
compilers and ony many machines Pascal was competitive too.
But there were no mass migration from C to other languages.
In fact C was gaining use and other languages lost their position.
--
Waldek Hebisch
Re: Taming The Switch-Statement
Author: Lawrence D’Oliveiro
Date: Tue, 20 Oct 2026 02:40
Date: Tue, 20 Oct 2026 02:40
16 lines
2307 bytes
2307 bytes
On Mon, 19 Oct 2026 08:46:58 -0000 (UTC), Waldek Hebisch wrote: > You do not win in the market by making easy switch from your product > to competitor product. You may want to make it easy to switch _to_ > your product. But you want to make switching to competing products > as hard as possible. “Vendor lock-in” -- that’s the old proprietary-software model. Customers are growing savvy to that sort of trick, which is why open-source software has become so popular. The most insidious form isn’t so much about the software, but about the proprietary data formats. If competitors’ software cannot read files containing the customers’ precious data accumulated over years of using a product, then the customer cannot switch to the competitor, even if they wanted to.
Re: Taming The Switch-Statement
Author: Lawrence D’Oliveiro
Date: Tue, 20 Oct 2026 02:44
Date: Tue, 20 Oct 2026 02:44
11 lines
1897 bytes
1897 bytes
On Tue, 20 Oct 2026 01:03:15 -0000 (UTC), Waldek Hebisch wrote: > Similarly, BCPL was too complicated, B and C were simplifications > and adaptations small machine. BCPL was a very bare-bones language -- it didn’t even have structs, or even much in the way of types. Every variable was an “integer”. Naming the variable didn’t return its value, but its address; you had to use an explicit “dereference” operator to get the variable value. C was certainly a more complicated language than BCPL.
Re: Taming The Switch-Statement
Author: Lawrence D’Oliveiro
Date: Tue, 20 Oct 2026 02:45
Date: Tue, 20 Oct 2026 02:45
7 lines
2162 bytes
2162 bytes
On Mon, 19 Oct 2026 19:38:38 -0400, Bob Duff wrote: > The "goto" is good enough for jumping out of nested loops. “Goto” leads inevitably to spaghetti code. Yes, we see that happening in the real world, all the time.
Re: Taming The Switch-Statement
Author: Janis Papanagnou
Date: Tue, 20 Oct 2026 03:01
Date: Tue, 20 Oct 2026 03:01
17 lines
2686 bytes
2686 bytes
On 2026-10-20 04:45, Lawrence D’Oliveiro wrote: > On Mon, 19 Oct 2026 19:38:38 -0400, Bob Duff wrote: > >> The "goto" is good enough for jumping out of nested loops. > > “Goto” leads inevitably to spaghetti code. [...] Not if you only use it in those rare cases to jump out of a loop and in a local context. - A 'break' LABEL is not better or worse than a 'goto' LABEL concerning an inherent "spaghetti structure". Janis PS: "inevitably" - yet another word of type like "unquestionably" (that we recently heard in another context). - Careful with adverbs, folks, especially with absolute ones in generalizing text contexts!
Re: Taming The Switch-Statement
Author: David Brown
Date: Tue, 20 Oct 2026 07:05
Date: Tue, 20 Oct 2026 07:05
56 lines
4358 bytes
4358 bytes
On 20/10/2026 00:28, Keith Thompson wrote: > David Brown <david.brown@hesbynett.no> writes: >> On 19/10/2026 12:50, Keith Thompson wrote: > [...] >>> The odd scoping rules for labels don't bother me either. They mean >>> you can't have two loops or switch statements with the same name in >>> the same function. I can barely imagine that being inconvenient. >> >> I can imagine that being a bit inconvenient in some cases, but I think >> the proposal in N3658 would simply and cleanly fix that. > [...] > > *If* the fact that labels (which are now also loop/switch names) > follow strange scope rules is a real problem, N3658 is probably > the best practical solution. I'm slightly uncomfortable with the > idea of an entity's scope depending on how it's used, not just how > it's defined. I think it introduces a complication to the language > without much real benefit. I can understand the feeling here - it would mean "L1: ; L1: ;" is fine until you also add "goto L1;". But it is simply saying that the real problem is not duplicate labels - it is ambiguity in the target label. > > But cleaner solutions are impractical. I think that is correct. > > IMHO the only really clean solution would be to make labels and > loop/switch names distinct, keep the existing scoping rules for > labels, and use more normal scoping rules for loop/switch names. > And if the "while NAME (...)" proposal were accepted, that's probably > how it should work. (But I prefer having the name as a prefix of the > loop or switch statement.) We cannot have an ideal solution here - there are always compromises when new features are added to existing languages. > > If N3658 were adopted, it wouldn't bother me much. I just don't > think it's necessary. > I do see benefits to it. I don't think it will make much difference to code in practice - after all, the great majority of functions in C do not have any labels, any gotos, or any use of multi-level breaks. But it conveniently negates one of the big disadvantages of the prefix label syntax for named control structures. There are code bases where there are macros containing loops that might benefit from this, and I can imagine it being helpful for generated C code (which is sometimes label-heavy).
Re: Taming The Switch-Statement
Author: David Brown
Date: Tue, 20 Oct 2026 07:18
Date: Tue, 20 Oct 2026 07:18
56 lines
4048 bytes
4048 bytes
On 19/10/2026 17:47, Tim Rentsch wrote:
> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
>
>> On 2026-10-18 12:48, David Brown wrote:
>>
>>> On 17/10/2026 01:29, Janis Papanagnou wrote:
>>>
>>>> On 2026-10-17 00:00, Keith Thompson wrote:
>>>>
>>>>> Tim Rentsch <tr.17687@z991.linuxsc.com> writes:
>>>>>
>>>>>> Keith Thompson <Keith.S.Thompson+u@gmail.com> writes:
>>>>>> [...]
>>>>>>
>>>>>>> There's a proposal for C2y to use goto labels as loop names, and a
>>>>>>> competing one to define a new syntax like "for NAME (;;)" :
>>>>>>> [...]
>>>>>>
>>>>>> I'm not particularly a fan of multi-level break/continue. But if
>>>>>> we're going to have one of these, the second ("for NAME (;;)") is
>>>>>> unquestionably better.
>>>>>
>>>>> Unquestionably? Why?
>>>>
>>>> Why would one question an opinion? ;-)
>>>
>>> Time didn't word it as a personal opinion - he made it clear that he
>>> doesn't think anyone else could have a different opinion.
>>
>> You've noticed my smiley? (There was no need for an explanation.)
>
> Anyone who thinks my statement "the second ("for NAME (;;)") is
> unquestionably better" was meant as a statement of fact rather
> than a statement of opinion is an idiot.
I, for one, read what you /wrote/ - not what you later claim you meant.
>
> I think most people can see that I am careful in my writing, and
> also that I make an effort to differentiate statements of opinion,
> statements of belief, and statements of fact. My remark above is
> no exception to that practice.
>
I think most people can see that you are /usually/ careful in your
writing. But you also occasionally make mistakes in the content of your
posts, and you regularly totally misjudge how your posts and your
wording comes across. One thing we know for sure is that you are
extremely reticent about admitting to being wrong, or that you worded a
post badly.
But what do I know? You branded me an "idiot" long ago - ironically
because I wrote opinions that were worded as though I believed they were
facts.
Re: Taming The Switch-Statement
Author: Keith Thompson
Date: Tue, 20 Oct 2026 07:45
Date: Tue, 20 Oct 2026 07:45
10 lines
2191 bytes
2191 bytes
Janis Papanagnou <janis_papanagnou+ng@hotmail.com> writes:
[...]
> Careful with adverbs, folks, especially with absolute ones in
> generalizing text contexts!
Absolutely!
--
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
Author: David Brown
Date: Tue, 20 Oct 2026 08:01
Date: Tue, 20 Oct 2026 08:01
154 lines
8439 bytes
8439 bytes
On 19/10/2026 23:28, bart wrote:
> On 19/10/2026 14:46, David Brown wrote:
>> On 19/10/2026 15:16, Janis Papanagnou wrote:
>>> On 2026-10-18 21:09, David Brown wrote:
>>>> On 18/10/2026 18:09, bart wrote:
>>>>> [...]
>>> [ declaration syntax ]
>>>
>>> (I just want to comment on a [not unimportant] detail...)
>>>
>>>>
>>>> You need to give things in the right order, or use parentheses, to
>>>> get the right "type expression". It's just like any other kind of
>>>> expression.
>>>>
>>>> The intention of the declaration syntax in C is that the declaration
>>>> order follows usage. [...]
>>>
>>> I think the first part is downplaying that languages typically indeed
>>> make a distinction between parenthesized expressions and declarations.
>>> Quite some other languages [not from the C-heritage] that I used all
>>> did not need to introduce "expression"-grouping for _declarations_ in
>>> the first place given their more consistent ways to declare entities.
>>>
>>> The second part is, as I had understood C's history, the idea behind
>>> how it got defined; needless to say that I think that was a bad idea.
>>> But that's what we've got! If they had dropped that requirement/idea
>>> the declaration syntax could have become "better" (more consistent,
>>> less cryptic, less convoluted, clearer). Now, after half a century,
>>> we just have to live with that, and folks who have "problems" with it
>>> should better not touch this language (or maybe not doing programming
>>> at all). The somewhat tragic aspect is that the "declaration follows
>>> use" idea was (IIRC) intended to _simplify_ the understanding of its
>>> concepts and use of the language; the consequences were seemingly not
>>> valued correctly.
>>>
>> There are a number of things that I don't particularly like about C's
>> declaration syntax, or where I think it would have been better if it
>> were different. But the "inside-to-outside" ordering is not one of
>> them. That is not because I think it is better or clearer than left-
>> to- right ordering, but because when I compare to, say, Pascal, it's
>> not a big issue for me. Far bigger are :
>>
>> 1. People put too much into a single type declaration, rather than
>> building types out of logical parts with a purpose and a name. They
>> don't do it as much as Bart likes to pretend, but some people do it
>> too much for my liking. The language doesn't force you to do that -
>> it's programmer style. IMHO there is never a reason for a "pointer to
>> an array of function pointers taking int and returning void" - no
>> matter what syntax is used.
>
> Then you have a peculiar and restricted coding style.
I don't believe so, no - at least, not compared to other code in my
field. It /is/ restricted, but so is everyone's coding style.
>
> (Funny that when I suggest that nested loop breaks are uncommon,
> everyone says I'm wrong! Some even write 200-line made-up examples to
> prove their point.)
I don't remember "everyone" saying you were wrong to say that nested
loop breaks are uncommon - in fact, I don't remember /anyone/ saying
that was wrong. A few people have suggested that they personally would
often find some kind of multi-level break useful, but I do not believe
many people think it is common, as a fraction of all C code they write.
(You really should cut down on the paranoia and the exaggerations.)
>
> These are two actual function pointer arrays from my projects (not C):
>
> []ref proc hosthandlers = ...
>
> [pclnames.len]ref proc(pcl) px_handlertable
>
> There is no reason to abstract away that function pointer type.
>
> You probably do so in C /because/ the type involves * () and [] but have
> somehow persuaded yourself that it just better that way.
Do you hear that whooshing noise? It is the sound of the point flying
far above your head.
Here is an example of some sensible function typedefs, all from
third-party code (so not my "peculiar" style)
struct tmrTimerControl;
typedef struct tmrTimerControl * TimerHandle_t;
typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
TimerHandle_t xTimerCreate( const char * const pcTimerName,
TickType_t xTimerPeriodInTicks,
UBaseType_t uxAutoReload,
void * pvTimerID,
TimerCallbackFunction_t pxCallbackFunction );
typedef void (*TaskFunction_t)( void * );
typedef BaseType_t (*TaskHookFunction_t)( void * );
typedef void (*altcp_err_fn)(void *arg, err_t err);
typedef void (*lwip_thread_fn)(void *arg);
typedef void (*tcpip_init_done_fn)(void *arg);
typedef void (*tcpip_callback_fn)(void *ctx);
typedef void (* sys_timeout_handler)(void *arg);
typedef void (*dns_found_callback)(const char *name,
const ip_addr_t *ipaddr, void *callback_arg);
Ask yourself why the typedefs are used. Look at the /names/. Those
last four are all from the same network stack library, and are all
typedefs for "void (*)(void*)". That function type could easily have
been written out in full in each declaration that used them. Yet the
actual functions using them specifically choose to use the type names
that are relevant at the time.
Do you really need me to spoon-feed you the reasons why this is all a
good idea? People name types because it makes their code clearer, more
robust, more flexible, more portable.
>
> Note that 'pcl' in my example /is/ a typedef; here it makes sense as it
> is used in 100s of places. This function pointer occurs in only one place.
I'm sorry, I had mistaken you for a programmer who wanted to write good,
clear programs. Naming things is not a shortcut to save keypresses.
>
> (The C version looks like: 'void (*name[N]))T)'. I used a tool and
> transcribed it, then I double-checked and found I'd written '(*name)[N]'
> not '(*name[N])'; I wouldn't have noticed.)
>
> BTW what name would be given to such a function pointer type? There is
> nothing obvious other than 'funcptr', but suppose there is more than one
> in scope?
I have no idea what your code is supposed to do, so I have no idea what
names would be good. Presumably you /do/ know what it is for - such as
what "pcl" means - so /you/ pick good names. Maybe "host_handler_fn" ?
>
> Something else strikes me about breaking up a complex type-decl sequence
> into a chain of typedefs: if you take that list of typedefs, and rotate
> it 90 degrees c/w, you have something that resembles the LTR
> representation!
>
If the details of the declaration syntax matter, you are doing it wrong.
Re: Taming The Switch-Statement
Author: David Brown
Date: Tue, 20 Oct 2026 08:25
Date: Tue, 20 Oct 2026 08:25
120 lines
6667 bytes
6667 bytes
On 19/10/2026 23:27, Janis Papanagnou wrote:
> On 2026-10-19 21:35, Michael S wrote:
>> On Mon, 19 Oct 2026 15:44:40 +0200
>> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
>>
>>> On 2026-10-18 18:32, Michael S wrote:
>>>> On Sun, 18 Oct 2026 18:11:18 +0200
>>>> Janis Papanagnou <janis_papanagnou+ng@hotmail.com> wrote:
>>>>>
>>>>> I don't recall to have used any language with infix-expressions
>>>>> that would have their monadic operators defined in postfix form.
>>>>
>>>> I am a Bear of Very Little Brain, and long words Bother Me.
>>>
>>> (If that quote is important for your argument, please explain.)
>>>
>>
>> Translation:
>> 1. I have no idea what unary * has to do with infix-expressions
>> 2. I don't appriciate use of the term "infix-expression" instead of more
>> common (in context of description of C and similar languages) term
>> 'binary operators'.
>> 3. I don't know what "monadic operators defined in postfix form" means
>> and have no plans to look for the meaning
>>
>
> I'm sorry, these are (AFAICT) common terms, and I thought obvious.
I am afraid your terminology is further from common use than you
thought. ("Common use" of course depends on the context of the user -
we are in the context of C programmers.) Your posts can be clearer if
you use appropriate terminology.
> So let me explain and amend with more text and examples...
>
> Point 1. - I gave the hint that in languages that support RPN
> (= Reverse Polish Notation) things like monadic postfix operators
> (= having just _one_ argument applied _after_ the operator) are the
> natural way of writing expressions. Less so in languages, which are
> the majority since decades, that support expressions with infix
> operators (= the operator arguments left and right of the operator).
>
RPN - Reverse Polish Notation - is certainly a well-known term, though
the abbreviation might seem out of place. "Postfix" is the term most
obvious in the context of C, as that is the term used in the standards.
And while "x y +" is clearly RPN, "x *" is not - it could be part of an
infix expression, or a unary postfix operator.
"Monadic" /can/ refer to single argument functions or operators. But it
can also mean something completely different - monadic operations are
operations that work on "packaged" types that unpack the value, apply a
function, and pack it in again. There is nothing of that kind in C (the
language or standard library), but it is becoming a familiar term for
users of C++ and is well-established in many other languages.
The C standard using "unary" for single-argument operators.
Similarly, "binary" is the normal term for two-argument operators, not
"dyadic". (Though I don't think "dyadic" has any other common meanings.)
> Point 2. - A "binary operator" may be the '*' in the expressions
> a * b typical infix notation (with parenthesis for precedence)
> a b * RPN
Normally known as "postfix", especially in C.
> * a b PN (Polish Notation)
There is no term "Polish Notation" - except as occasionally used to mean
/postfix/ as a short form of "Reverse Polish Notation". RPN was
invented, or at least popularised, by the Polish logician Jan
Łukasiewicz (I admit to looking that up on Wikipedia!). There is no
"PN" opposite.
>
> A "binary operator" is something different from an "infix expression"
> (the first one of the three; the others are RPN and PN examples).
> That's why I took the appropriate term to explain what I intended to
> explain.
Yes, binary operators can be prefix, infix or postfix.
>
> Point 3. - "monadic" (see point 1). Applying to postfix form is best
> explained on another example; assume RPN
> a - monadic (unary) minus (on one argument)
Or, as the C world calls it, a postfix unary operator.
> a b - dyadic (binary) minus (difference of two arguments)
>
Or, as the C world calls it, a syntax error or a refugee from
comp.lang.forth.
> Hope the terms are clear now. Now consider our original case, e.g.
>
> a * *b ... multiply and dereference
> a - -b ... subtract and negate
>
> as soon as we parse the second operator we know its kind. With postfix
> operators we'd have (assuming same semantics but with postfix operators)
>
> a * b * ... now what is the second '*' at that point of parsing?
> a - b - ... we don't expect that second '-' to be a negation.
>
> The compilers can handle every variant. For the users it's different;
> usually they seem to prefer unary operators to be prefixed (YMMV).
>
> The question (concerning "C") was; would it have been "better" (in any
> respect) if the dereferencing operator would have been defined in "C"
> as postfix operator (as you seem to prefer).
>
> Janis
>
Re: Taming The Switch-Statement
Author: Tim Rentsch
Date: Tue, 20 Oct 2026 09:53
Date: Tue, 20 Oct 2026 09:53
38 lines
2680 bytes
2680 bytes
cross@spitfire.i.gajendra.net (Dan Cross) writes:
> In article <11b285v$121v2$2@dont-email.me>,
> David Brown <david.brown@hesbynett.no> wrote:
>
>> On 17/10/2026 01:29, Janis Papanagnou wrote:
>>
>>> On 2026-10-17 00:00, Keith Thompson wrote:
>>>
>>>> Tim Rentsch <tr.17687@z991.linuxsc.com> writes:
>>>>
>>>>> Keith Thompson <Keith.S.Thompson+u@gmail.com> writes:
>>>>> [...]
>>>>>
>>>>>> There's a proposal for C2y to use goto labels as loop names, and a
>>>>>> competing one to define a new syntax like "for NAME (;;)" :
>>>>>> [...]
>>>>>
>>>>> I'm not particularly a fan of multi-level break/continue. But if
>>>>> we're going to have one of these, the second ("for NAME (;;)") is
>>>>> unquestionably better.
>>>>
>>>> Unquestionably? Why?
>>>
>>> Why would one question an opinion? ;-)
>>
>> Time didn't word it as a personal opinion - he made it clear that he
>> doesn't think anyone else could have a different opinion.
>
> Tim often makes it sound as though he believes that his opinions
> are facts.
I invite you to compare the statements made about David Parnas and
his advice on software development, first those in the original
edition of The Mythical Man-Month and second those in the revised
(20th Anniversary) edition of MM-M, both of course by Fred Brooks.
I learned a lot from Fred Brooks.
Re: Taming The Switch-Statement
Author: bart
Date: Tue, 20 Oct 2026 11:41
Date: Tue, 20 Oct 2026 11:41
173 lines
8149 bytes
8149 bytes
On 20/10/2026 09:01, David Brown wrote:
> On 19/10/2026 23:28, bart wrote:
>> (Funny that when I suggest that nested loop breaks are uncommon,
>> everyone says I'm wrong! Some even write 200-line made-up examples to
>> prove their point.)
>
> I don't remember "everyone" saying you were wrong to say that nested
> loop breaks are uncommon - in fact, I don't remember /anyone/ saying
> that was wrong.
(There was a LOT of antipathy towards my idea to fix the common case of
'loop-break' clashing with 'switch-break', BECAUSE it did not fix the
problem of nested loop-break, which is uncommon, even though that wasn't
the aim.)
>> There is no reason to abstract away that function pointer type.
>>
>> You probably do so in C /because/ the type involves * () and [] but
>> have somehow persuaded yourself that it just better that way.
>
> Do you hear that whooshing noise? It is the sound of the point flying
> far above your head.
>
> Here is an example of some sensible function typedefs, all from third-
> party code (so not my "peculiar" style)
>
> typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
>
> TimerHandle_t xTimerCreate( const char * const pcTimerName,
> TickType_t xTimerPeriodInTicks,
> UBaseType_t uxAutoReload,
> void * pvTimerID,
> TimerCallbackFunction_t pxCallbackFunction );
>
> typedef void (*lwip_thread_fn)(void *arg);
> typedef void (*tcpip_init_done_fn)(void *arg);
> typedef void (*tcpip_callback_fn)(void *ctx);
> typedef void (* sys_timeout_handler)(void *arg);
> typedef void (*dns_found_callback)(const char *name,
> const ip_addr_t *ipaddr, void *callback_arg);
This is the kind of C I find hard to read. There are lots of typedefs
but few uses of those typedefs that I can see, so I don't know how much
difference they make.
Except here:
typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
TimerHandle_t xTimerCreate( const char * const pcTimerName,
TickType_t xTimerPeriodInTicks,
UBaseType_t uxAutoReload,
void * pvTimerID,
TimerCallbackFunction_t pxCallbackFunction );
Without the typedef, I believe it would just be this:
TimerHandle_t xTimerCreate( const char * const pcTimerName,
TickType_t xTimerPeriodInTicks,
UBaseType_t uxAutoReload,
void * pvTimerID,
void (*pxCallbackFunction)(TimerHandle_t));
(I've left out the parameter name of the callback function, as I don't
believe it is that useful.
I've left in the regular parameter names, even though C doesn't need
them, but they are quite heavy - you don't really need those
Hungarian-style prefixes.)
Well, I guess this buys you one thing: the parameter name for the last
parameter is to the right of its type, rather than be inside it. But a C
expert should not be fazed by that.
Here is the same function as I might write it in an alternative syntax.
I've kept the same names, but changed case-style and removed prefixes
and suffixes. I've capitalised user-type names:
func TimerCreate( # (retain case if FFI import)
ichar timername,
Ticktype timerperiodinticks,
Ubasetype autoreload,
ref void timerid,
ref proc(Timerhandle) callbackfn)
In this form, it's hard to see what benefit a typedef would give for
that last parameter; it is simple enough.
> Ask yourself why the typedefs are used. Look at the /names/. Those
> last four are all from the same network stack library, and are all
> typedefs for "void (*)(void*)".
Until you mentioned it, I hadn't noticed. So typedef has done a good job
of hiding that useful fact! But looking more closely, it is the first
four of the last five.
Let's take one:
typedef void (*lwip_thread_fn)(void *arg);
That 'arg' is not much use for a start (other than being a hint that
this particular (...) is where the parameters go).
So, maybe this is used like this:
void F(lwip_thread_fn lwip_thread_callback);
Here you have two identifiers imparting the sort kind of information; a
tautology.
If that function pointer pattern is common, or recurs in a suite of
functions, I might also have used a typedef, but with a common name.
Then only one would be needed, say:
typedef void (*stack_callbackfn)(void);
I might have done the same in that alternate syntax as it would start to
get cluttery: 'ref proc(ref void)', but also in order to define that
common pattern in one place.
>> Note that 'pcl' in my example /is/ a typedef; here it makes sense as
>> it is used in 100s of places. This function pointer occurs in only one
>> place.
>
> I'm sorry, I had mistaken you for a programmer who wanted to write good,
> clear programs. Naming things is not a shortcut to save keypresses.
Isn't that one of the main uses of typedefs? So as to give a handy,
'euphonious' one-token alias to an elaborate typedef.
It also allows you to change the type in one place without having to
update hundreds of instances.
It also allows the type to be opaque.
Saving keypresses is bonus benefit, but if it is shorter, then it can
also help readability as other critical elements are not overshadowed.
So I'm not sure what objection you have to this particular use of it.
Here is the one place I do remember using typedef for a function pointer
(from an old project, not in C):
type fnptr = ref proc
repeat
(fnptr(pcptr^))^()
until stopped
It's used as a cast, but reason I have it is because with simple cast
syntax, which is 'T(X)', the meaning without it would be ambiguous (a
grammar issue that I might fix one day).
Rather than fallback to standard cast syntax (which is 'cast(X, T)'),
this was tidier.
>> BTW what name would be given to such a function pointer type?
> I have no idea what your code is supposed to do,
It's a table of function pointers! All sharing the same signature.
That's pretty generic. Is it really that hard to guess? You don't need
to know what they do, other than at some point they will be called as
handlertable[i](arg).
Re: Taming The Switch-Statement
Author: Dan Cross
Date: Tue, 20 Oct 2026 12:22
Date: Tue, 20 Oct 2026 12:22
32 lines
2194 bytes
2194 bytes
In article <86tsmgog01.fsf@linuxsc.com>, Tim Rentsch <tr.17687@z991.linuxsc.com> wrote: >cross@spitfire.i.gajendra.net (Dan Cross) writes: >> [snip] >> Tim often makes it sound as though he believes that his opinions >> are facts. > >I invite you to compare the statements made about David Parnas and >his advice on software development, first those in the original >edition of The Mythical Man-Month and second those in the revised >(20th Anniversary) edition of MM-M, both of course by Fred Brooks. I suppose that you must think that this is some sort of profound statement, and that by assigning this kind of pedagogical exercise that you expect me to learn something relevant. But I find this sophomoric imperative grotesquely arrogant. Like Keith, I don't need you to give me homework assignments. I have some suspicion about what you are referring to from Brooks, but I am not going to waste my time chasing down what you can't be bothered to just say. If you mean to say something, then say it, or do not. In either case, do not presume to waste my or anyone else's time with poor attempts at the socratic method. "I invite you...", indeed. >I learned a lot from Fred Brooks. That's nice. So did I. - Dan C.
Re: Taming The Switch-Statement
Author: David Brown
Date: Tue, 20 Oct 2026 12:58
Date: Tue, 20 Oct 2026 12:58
329 lines
15285 bytes
15285 bytes
On 20/10/2026 13:41, bart wrote:
> On 20/10/2026 09:01, David Brown wrote:
>> On 19/10/2026 23:28, bart wrote:
>
>>> (Funny that when I suggest that nested loop breaks are uncommon,
>>> everyone says I'm wrong! Some even write 200-line made-up examples to
>>> prove their point.)
>>
>> I don't remember "everyone" saying you were wrong to say that nested
>> loop breaks are uncommon - in fact, I don't remember /anyone/ saying
>> that was wrong.
>
> (There was a LOT of antipathy towards my idea to fix the common case of
> 'loop-break' clashing with 'switch-break', BECAUSE it did not fix the
> problem of nested loop-break, which is uncommon, even though that wasn't
> the aim.)
It is correct that the idea of having a "loop-break" statement was
considered and quickly rejected by people looking at multi-level breaks.
It would be silly, when first making a language change to handle one
type of coding situation, to pick a special case when a more general
solution could be used. I don't think anyone was arguing that the
desire for breaking out of nested loops was /common/, but I don't think
many people felt breaking out of a switch in a loop was common either.
Both needs are relatively rare in general C coding.
But while the consensus is that a "loop-break" statement is not worth
adding to C, that is a completely different thing than claiming that
"everyone" said you were wrong to say nested loop breaks are common!
So - again - please cut the paranoia and exaggerations, and /read/ what
people write, rather than the conspiracies you imagine they write.
>
>>> There is no reason to abstract away that function pointer type.
>>>
>>> You probably do so in C /because/ the type involves * () and [] but
>>> have somehow persuaded yourself that it just better that way.
>>
>> Do you hear that whooshing noise? It is the sound of the point flying
>> far above your head.
>>
>> Here is an example of some sensible function typedefs, all from third-
>> party code (so not my "peculiar" style)
>>
>
>> typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
>>
>> TimerHandle_t xTimerCreate( const char * const pcTimerName,
>> TickType_t xTimerPeriodInTicks,
>> UBaseType_t uxAutoReload,
>> void * pvTimerID,
>> TimerCallbackFunction_t pxCallbackFunction );
>>
>
>> typedef void (*lwip_thread_fn)(void *arg);
>> typedef void (*tcpip_init_done_fn)(void *arg);
>> typedef void (*tcpip_callback_fn)(void *ctx);
>> typedef void (* sys_timeout_handler)(void *arg);
>> typedef void (*dns_found_callback)(const char *name,
>> const ip_addr_t *ipaddr, void *callback_arg);
>
>
> This is the kind of C I find hard to read. There are lots of typedefs
> but few uses of those typedefs that I can see, so I don't know how much
> difference they make.
Yes, sorry, I should have posted tens of thousands of lines of C code
using these. I'm sure that would have made things much clearer than a
couple of extracted examples.
But let us take a concrete example. These network functions are from
the LWIP network stack, which is designed to be used on small embedded
systems that may not have any kind of OS - so it uses call-backs for
asynchronous programming.
An example API function is this :
err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr,
dns_found_callback found, void *callback_arg)
The returned "err_t" can be "ERR_OK" (indicating the "hostname" is in
the DNS cache and *addr is set to the IP), "ERR_ARG" for argument
errors, or "ERR_INPROGRESS" to indicate that the stack is looking up the
DNS name, and will call the callback when there is a final result or
timeout.
Without typedef's, that function signature would be something like :
signed char dns_gethostbyname(const char *hostname, struct ip_addr
*addr, void (*found)(const char *name, const struct ip_addr
*ipaddr, void *callback_arg), void *callback_arg);
Do you expect anyone to believe you if you claim this is easier to read
than the real declaration using typedefs? I'll believe you if you say
you find the original hard to read - but not if you claim the
"untypedef'ed" version is clearer.
The typedefs let you understand the code piece by piece.
A "dns_found_callback" is a callback function called when a dns lookup
has finished - that's clear from its name. It is called with arguments
the name that was looked up, the ip address that was found, and a
user-supplied extra argument that can be used as you want. That's
simple and clear.
The "dns_gethostbyname" function is a function to find a host's IP
address, given its name - that's clear from the name. It is called with
the name to look up, a pointer to a place to store the resulting IP
address, a callback function of type "dns_found_callback" if it can't
answer immediately, and a user-supplied extra argument for the callback
function. This is again, simple and clear.
>
> Except here:
>
> typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
>
> TimerHandle_t xTimerCreate( const char * const pcTimerName,
> TickType_t xTimerPeriodInTicks,
> UBaseType_t uxAutoReload,
> void * pvTimerID,
> TimerCallbackFunction_t pxCallbackFunction );
>
> Without the typedef, I believe it would just be this:
>
> TimerHandle_t xTimerCreate( const char * const pcTimerName,
> TickType_t xTimerPeriodInTicks,
> UBaseType_t uxAutoReload,
> void * pvTimerID,
> void (*pxCallbackFunction)(TimerHandle_t));
>
> (I've left out the parameter name of the callback function, as I don't
> believe it is that useful.
>
> I've left in the regular parameter names, even though C doesn't need
> them, but they are quite heavy - you don't really need those Hungarian-
> style prefixes.)
/C/ does not need the parameter names - /programmers/ need them, because
they tell you want they do. Omitting them is as smart as calling all
your functions "foo1", "foo2", etc., just because C does not require
sensible names.
The point of using typedefs here is that they make the xTimerCreate()
function declaration simpler and clearer, and it tells the programmer
what is going on. It tells the programmer that the parameter is a
TimerCallbackFunction - not just any old function that takes a
TimerHandle_t parameter. The programmer knows that a suitable argument
is their "flash_the_green_led" function, but not their
"initialise_timer" function that happens coincidentally to have the same
signature.
>
> Well, I guess this buys you one thing: the parameter name for the last
> parameter is to the right of its type, rather than be inside it. But a C
> expert should not be fazed by that.
>
> Here is the same function as I might write it in an alternative syntax.
>
> I've kept the same names, but changed case-style and removed prefixes
> and suffixes. I've capitalised user-type names:
>
> func TimerCreate( # (retain case if FFI import)
> ichar timername,
> Ticktype timerperiodinticks,
> Ubasetype autoreload,
> ref void timerid,
> ref proc(Timerhandle) callbackfn)
>
> In this form, it's hard to see what benefit a typedef would give for
> that last parameter; it is simple enough.
I am glad I don't have to work with your code - whatever language you
use. The number one skill for programmers is picking good names, and
you flumped that one.
>
>
>> Ask yourself why the typedefs are used. Look at the /names/. Those
>> last four are all from the same network stack library, and are all
>> typedefs for "void (*)(void*)".
>
> Until you mentioned it, I hadn't noticed. So typedef has done a good job
> of hiding that useful fact! But looking more closely, it is the first
> four of the last five.
It is not "hiding a useful fact" - it is abstracting away from an
unintended coincidence. My own preference is to use stronger types,
precisely so that things could not be mixed up. I'd have :
typedef struct { void * arg; } lwip_thread_arg;
typedef void (*lwip_thread_fn)(lwip_thread_arg * arg);
typedef struct { void * arg; } tcpip_init_done_arg;
typedef void (*tcpip_init_done_fn)(tcpip_init_done_arg * arg);
(If I were to go back in time and change things in C, I'd make "typedef"
define new types, not type aliases.)
>
> Let's take one:
>
> typedef void (*lwip_thread_fn)(void *arg);
>
> That 'arg' is not much use for a start (other than being a hint that
> this particular (...) is where the parameters go).
>
> So, maybe this is used like this:
>
> void F(lwip_thread_fn lwip_thread_callback);
>
> Here you have two identifiers imparting the sort kind of information; a
> tautology.
You don't need to duplicate the name when it is not helpful - and you
certainly should not do so when it is clearly wrong (a thread function
is not a callback function, even if the signatures match). A real
function signature using this type is :
sys_thread_t sys_thread_new(const char *name, lwip_thread_fn thread,
void *arg, int stacksize, int prio);
>
> If that function pointer pattern is common, or recurs in a suite of
> functions, I might also have used a typedef, but with a common name.
> Then only one would be needed, say:
>
> typedef void (*stack_callbackfn)(void);
/You/ might have written that, but it would be significantly worse code.
You are obsessed with the details of the syntax of the type, instead
of looking at what it represents and what it will mean in the code.
There can be occasional uses for "generic" names, like :
typedef void (*fp_void)(void);
just as there are uses for generic "int" types rather than types like
"size_t", "int32_t", "TickType_t", etc. But using well-named types
conveys vital information. Using badly named types, or re-using named
types inappropriately, makes code worse.
>
> I might have done the same in that alternate syntax as it would start to
> get cluttery: 'ref proc(ref void)', but also in order to define that
> common pattern in one place.
>
>>> Note that 'pcl' in my example /is/ a typedef; here it makes sense as
>>> it is used in 100s of places. This function pointer occurs in only
>>> one place.
>>
>> I'm sorry, I had mistaken you for a programmer who wanted to write
>> good, clear programs. Naming things is not a shortcut to save
>> keypresses.
>
> Isn't that one of the main uses of typedefs? So as to give a handy,
> 'euphonious' one-token alias to an elaborate typedef.
No, it should not be your main use of typedef - but it might
occasionally be a reason.
>
> It also allows you to change the type in one place without having to
> update hundreds of instances.
>
> It also allows the type to be opaque.
Now you are beginning to understand! Yes, these are two key reasons for
typedefs.
>
> Saving keypresses is bonus benefit, but if it is shorter, then it can
> also help readability as other critical elements are not overshadowed.
I agree - but that is a bonus, not an aim in itself. There is a balance
to be found between being too verbose, and not being explicit enough.
The "right" balance point depends very much on the context, the code,
and the target audience.
>
> So I'm not sure what objection you have to this particular use of it.
I don't object to having shorter aliases when appropriate. I object to
it as a prime motivation.
>
> Here is the one place I do remember using typedef for a function pointer
> (from an old project, not in C):
>
> type fnptr = ref proc
>
> repeat
> (fnptr(pcptr^))^()
> until stopped
>
> It's used as a cast, but reason I have it is because with simple cast
> syntax, which is 'T(X)', the meaning without it would be ambiguous (a
> grammar issue that I might fix one day).
>
> Rather than fallback to standard cast syntax (which is 'cast(X, T)'),
> this was tidier.
>
>>> BTW what name would be given to such a function pointer type?
>
>> I have no idea what your code is supposed to do,
>
> It's a table of function pointers! All sharing the same signature.
I can't see any use in a table of function pointers. I can see a use in
a table of event handlers, a table of timer callback functions, a table
of state machine state handlers, etc.
It's like saying you have an array of "int". No, you have an array of
the days in each month of the year, or an array of timestamps of
keypresses, or an array of the cost of different coffee mugs.
>
> That's pretty generic. Is it really that hard to guess? You don't need
> to know what they do, other than at some point they will be called as
> handlertable[i](arg).
>
That is why I guessed "host_handler_fn" as a name, but you snipped that.
Re: Taming The Switch-Statement
Author: bart
Date: Tue, 20 Oct 2026 14:11
Date: Tue, 20 Oct 2026 14:11
161 lines
7258 bytes
7258 bytes
On 20/10/2026 02:03, Waldek Hebisch wrote:
> bart <bc@freeuk.com> wrote:
>>
>> OK. But they HAD to create C? There were quite a few languages in the
>> early 70s too: like Pascal, Fortran, PL/I, Coral-66, plus of course BCPL
>> and B. So why a new one?
>
> You ignore fact that Ritche wanted reasonably fast code from
> very simple compiler.
According to DC's quote from HOPL, it was also more fun to create a new
language.
> PL/I had most needed features. But PL/I was a big language,
> to run on small machine they would have to take tiny subset
> and then add extentions. Basicaly they would end up with a
> language which is very far from PL/I.
There were PL/360 and PL/M, although those were more specific, more
'machine-oriented' languages. (I implemented one for PDP10 but it was a
port of a systems language from a GEC machine.)
Anyway, a more general subset could have been used.
> Similarly, BCPL was too complicated, B and C were simplifications
> and adaptations small machine.
>
> I think that Pascal was too late: nominally it was created earlier
> but I think that it was available to Bell Labs only after they
> did initial work leading to C. And Pascal shared problem of
> speed on small machines. Note that later UCSD Pascal which
> run on micros compiled to interpreted bytecode, which significantly
> reduced performance.
It would not have been hard to use Pascal as a starting point for a
workable systems language. Wirth wouldn't have approved, but his
languages were too pure, too academic; some of us had things we needed
to get done!
Here I mean adapting Pascal for a competing systems language.
In my hands some aspects would be simplified (eg. no nested functions,
no closures), thus making it easier to generate decent code with a
simple compiler.
>
>> FORTRAN syntax looked nothing like C! Unless you mean the general
>> pattern of 'INTEGER A, B' which was shared by half of all languages.
>
> I think more pattern of
>
> INTEGER A(20), B
>
> which has similar structure to C variable declarations.
OK. That was typical for the time. But in Fortran it didn't get much
more complicated than that. Maybe 2D arrays and so on.
> Of course,
> FORTRAN had no pointers (and structures or unions), so Ritche had
> to invent syntax for them.
There were three languages from that era that I know had pointers or
references, and which allowed composing arbitrary types with arrays and
pointers, two of which were Algol68 and Pascal.
Both used a 100% LTR form.
The other was C. There, several choices were made:
* To start with that Fortran style except that [] are used
* To decree that that 'A[20]' syntax is supposed to match indexing of
A as it might appear in an expression
* To introduce "*" as a prefix dereference operator in expressions ...
* ... which then means that a prefix "*" appears in the declaration too
* A further complication was to allow function pointers within that a
declaration list
* Yet one more which came later was to add 'const', where placement now
gets confusing
But to stay with pointers, take this expression:
*A[i]
C precedence rules mean this is parsed as *(A[i]), which means that a
type written as 'T *A[N]' must be an array of pointers to T (I had to
think for a few seconds!).
But suppose you wanted a pointer to array of T? The expression for that
would be:
(*A)[i]
And so the declaration has to be 'T (*A)[N]' too.
So it is unfortunate that parentheses used to control precedence in an
expression now also have to appear in type declarations (where they are
often next to () used for parameter lists, for further confusion).
==============================================
So, what would have happened with a postfix deref op? (Ignore whether
'*' would still be a good choice.) My first example would be this:
A*[i]
Here, it would mean that A is dereferenced, then indexed; A must then be
a pointer to an array of T.
But suppose we wanted the original array of pointers to T, where you
index first then dereference. That is written like this:
A[i]*
You simply swap the order of [] and *.
So, PARENTHESES HAVE BEEN ELIMINATED for purpose of disambiguating
array/pointer and pointer/array, both within expressions and within
type-declarations.
How about that? Further, most of the type-spec is now LTR; only the
base-type has to stay on the left. Access terms in expressions will be
fully LTR.
> IMO C suffers because typedef was added late in the game and
> function prototypes are much later. Prototypes need types and
> to get it one needs "hole" in variable declaration. Where the
> hole should be is specified by the C syntax, but placement of
> hole is probably least clear aspect of declarations.
I thought that 'hole' was where 'int A[10]' mean one thing in normal
declaration but another within a parameter list.
> IMO C declaration syntax was a mistake, but as real life shows
> it was not a fatal mistake, people can adapt.
A mistake that could so easily have been avoid by choosing a different
precedence as shown above. Did none of the thousand people working at
Bell Labs (according to a comment in DC's follow-ip) spot this and say
anything?
Had no-one even glanced at a Pascal spec, if there was no working copy?
It would have transformed C type syntax.
(ACTUALLY IT IS NOT TOO LATE. A secondary postfix deref op could have
been added. This could have been done 50 years ago, with the original
eventually deprecated.
But this is a common theme of mine whether I perceive a problem that
people grudgingly admit might not be idea. But nothing was ever done to
fix it even after decades.)
Re: Taming The Switch-Statement
Author: Janis Papanagnou
Date: Tue, 20 Oct 2026 14:56
Date: Tue, 20 Oct 2026 14:56
155 lines
8366 bytes
8366 bytes
On 2026-10-20 10:25, David Brown wrote:
> On 19/10/2026 23:27, Janis Papanagnou wrote:
>> On 2026-10-19 21:35, Michael S wrote:
>>> [...]
>>
>> I'm sorry, these are (AFAICT) common terms, and I thought obvious.
>
> I am afraid your terminology is further from common use than you
> thought.
I'm afraid you are wrong here; in several ways. I'll expand below.
> ("Common use" of course depends on the context of the user -
> we are in the context of C programmers.) Your posts can be clearer if
> you use appropriate terminology.
>
>
>> So let me explain and amend with more text and examples...
>>
>> Point 1. - I gave the hint that in languages that support RPN
>> (= Reverse Polish Notation) things like monadic postfix operators
>> (= having just _one_ argument applied _after_ the operator) are the
>> natural way of writing expressions. Less so in languages, which are
>> the majority since decades, that support expressions with infix
>> operators (= the operator arguments left and right of the operator).
>>
>
> RPN - Reverse Polish Notation - is certainly a well-known term, though
> the abbreviation might seem out of place.
I don't know why you think it would be "out of place". Since I gave
an explanation that made use of that concept I named it, and since
Michael had expressed difficulties with some of my (what I thought
to be commonly known, even here) terms I presented "RPN" with its
explicit meaning as you see above. (It's IMO good style to "explain"
acronyms when first used; but sadly - especially also here! - we
rarely see that, so I find it strange that you mention that at all.)
> "Postfix" is the term most
> obvious in the context of C, as that is the term used in the standards.
It's not about being obvious in context of C, it's about accuracy
of the used term in the context of my conceptual explanations.
(If I'd intended to explain something concerning the C-definition I
probably might have used the C-standard term. But I was explaining
something principle and used standard and common CS terminology.)
>
> And while "x y +" is clearly RPN, "x *" is not - it could be part of an
> infix expression, or a unary postfix operator.
Sure. If you reinspect my post you'll see that I used that term in
context of "x y +" and not in context of "a * b * ..." that I used
later. So your comment here is just unnecessary noise and void.
>
> "Monadic" /can/ refer to single argument functions or operators.
In CS I learned that "monadic" very specifically has the meaning I
used it for. - /Britannica/ (for example) [also] explains:
"Monadic and dyadic operators refer to the number of arguments
or operands an operator takes"
As an intermediate _general_ note; please accept that I use common
CS terms if I'm speaking about programming languages in general and
about design concepts. - I know and acknowledge that such terms are
often redefined (for specific contexts) or regularly misused. Don't
expect me to deliberately blur my language to express something for
an audience that *might* not have knowledge beyond "C". (I'd think
most of the audience here knows the CS terminology, though. If not
then I'll be glad to explain.)
> But it
> can also mean something completely different - monadic operations are
> operations that work on "packaged" types that unpack the value, apply a
> function, and pack it in again. There is nothing of that kind in C (the
> language or standard library), but it is becoming a familiar term for
> users of C++ and is well-established in many other languages.
(I know "many other languages" but don't recall to have seen mentioned
that word in another language with a meaning other than explained. So
I cannot know that it was given another meaning in some other special
area (like "packed types"). But I'd also expect that IT people at least
know the common CS terms.)
>
> The C standard using "unary" for single-argument operators.
>
> Similarly, "binary" is the normal term for two-argument operators, not
> "dyadic". (Though I don't think "dyadic" has any other common meanings.)
If we compare in discussions monadic and dyadic operators it would be
more a terminology issue with "unary" since the counterpart would then
be "binary", and "binary" is a homonymous word in that area and also on
that explanation level. - I prefer a most fitting choice of words.
And I'm sorry if some cannot follow my post because of that. But I'm
willing to explain if some terms are not known to some here; just ask.
>
>> Point 2. - A "binary operator" may be the '*' in the expressions
>> a * b typical infix notation (with parenthesis for precedence)
>> a b * RPN
>
> Normally known as "postfix", especially in C.
"Normally" I've seen that notation called RPN sometimes also as postfix
notation. (Please don't try to teach a duck swimming. And I suggest to
not join the club of folks who generalize based on opinions with words
like "normally".)
>
>> * a b PN (Polish Notation)
>
> There is no term "Polish Notation" -
My academic education as well as some [well reputed] online resources
disagree with you. (I wonder why you didn't check your _opinion_ here!)
> except as occasionally used to
> mean /postfix/ as a short form of "Reverse Polish Notation". RPN was
> invented, or at least popularised, by the Polish logician Jan
> Łukasiewicz (I admit to looking that up on Wikipedia!). There is no
> "PN" opposite.
Oh, so you have just missed it! - Retry...
https://en.wikipedia.org/wiki/Polish_notation
And next time better stay quiet instead of trying to play the smartass
without need! (It's really not necessary to post as much as you do.)
>
>>
>> A "binary operator" is something different from an "infix expression"
>> (the first one of the three; the others are RPN and PN examples).
>> That's why I took the appropriate term to explain what I intended to
>> explain.
>
> Yes, binary operators can be prefix, infix or postfix.
You don't need to confirm that. (It's common knowledge.)
> [ snip rest ]
(I've got tired and bored about your post.) :-/
But thanks for making it obvious that I cannot expect common and long
existing CS terms to be generally understood here.
I admit, that I might have made a wrong assumption about CS knowledge
here; before your post I thought it were just one or two individuals.
(Now my guess would be that it could be three or four individuals.)
Janis
Re: Taming The Switch-Statement
Author: David Brown
Date: Tue, 20 Oct 2026 15:02
Date: Tue, 20 Oct 2026 15:02
198 lines
8928 bytes
8928 bytes
On 20/10/2026 16:11, bart wrote: > The other was C. There, several choices were made: > > * To start with that Fortran style except that [] are used > > * To decree that that 'A[20]' syntax is supposed to match indexing of > A as it might appear in an expression > > * To introduce "*" as a prefix dereference operator in expressions ... > > * ... which then means that a prefix "*" appears in the declaration too > > * A further complication was to allow function pointers within that a > declaration list I don't see a problem with that. If you need to declare a function pointer, you need to declare it in a declaration list. To me, the big disadvantage of C's declaration syntax is that it lets you declare things of different (but related) types in the same declaration. I don't have a problem with : int (*my_func_pointer)(int); int my_array[20]; but I /do/ have a problem with : int (*my_func_pointer)(int), my_array[20]; or, more common and therefore worse : int * a, b; The way to deal with this is, of course, simply not writing such mixed declarations. But some people /do/ - living with other peoples' code is the bane of all programmers. I am confident that there could have been a nicer syntax, and function pointer (or function type) syntax is particularly ugly. But it works well enough in practice that I cannot see it as a problem or even inconvenience. > > * Yet one more which came later was to add 'const', where placement now > gets confusing Some people do find it hard to understand the difference between : const int * p; int * const q; const int * const r; I note that this is despite the clear left-to-right nature of "const" here. Many newbie mistakes with const will be caught by the compiler, and once you get used to it, you should be fine. > > But to stay with pointers, take this expression: > > *A[i] > > C precedence rules mean this is parsed as *(A[i]), which means that a > type written as 'T *A[N]' must be an array of pointers to T (I had to > think for a few seconds!). If you instead forget that you can declare more than one thing in one declaration, you can write : T* A[i]; Then it is quite clear. > > But suppose you wanted a pointer to array of T? The expression for that > would be: > > (*A)[i] > > And so the declaration has to be 'T (*A)[N]' too. Yes. Declaration syntax follows usage. (If you don't like the operator precedence, or the fact that dereferencing is pre-fix in C, unlike, say, Pascal, then that's an orthogonal dislike.) > > So it is unfortunate that parentheses used to control precedence in an > expression now also have to appear in type declarations (where they are > often next to () used for parameter lists, for further confusion). You know how to use typedefs to make code clearer. Complicated types are a minority. Most object declarations are either things, arrays of things, or pointers to things - not combinations of these. And most function declarations are just function declarations, not arrays of function pointers or other complex types. > > ============================================== > > So, what would have happened with a postfix deref op? (Ignore whether > '*' would still be a good choice.) My first example would be this: > > A*[i] > > Here, it would mean that A is dereferenced, then indexed; A must then be > a pointer to an array of T. > > But suppose we wanted the original array of pointers to T, where you > index first then dereference. That is written like this: > > A[i]* > > You simply swap the order of [] and *. > > So, PARENTHESES HAVE BEEN ELIMINATED for purpose of disambiguating > array/pointer and pointer/array, both within expressions and within > type-declarations. Agreed. But does that make a significant difference? I don't think so. I'd have to see a lot more real-life examples to get a feeling for whether postfix dereference would be better or worse than prefix - saving the occasional parentheses is not sufficient. > > How about that? Further, most of the type-spec is now LTR; only the > base-type has to stay on the left. Access terms in expressions will be > fully LTR. > >> IMO C suffers because typedef was added late in the game and >> function prototypes are much later. Prototypes need types and >> to get it one needs "hole" in variable declaration. Where the >> hole should be is specified by the C syntax, but placement of >> hole is probably least clear aspect of declarations. > > I thought that 'hole' was where 'int A[10]' mean one thing in normal > declaration but another within a parameter list. That's a different thing entirely. (And while I don't find it confusing that array and pointer parameters mean the same thing in C, I do see it as a wasted opportunity for better static checking and optimisation of code.) > >> IMO C declaration syntax was a mistake, but as real life shows >> it was not a fatal mistake, people can adapt. > > A mistake that could so easily have been avoid by choosing a different > precedence as shown above. Did none of the thousand people working at > Bell Labs (according to a comment in DC's follow-ip) spot this and say > anything? I suspect the folks at Bell Labs were too busy writing real code to be bothered by how confused you would be with artificially complex types. Life is full of little decisions that, with hindsight, might have been sub-optimal choices but are nonetheless good enough in practice. C's declaration syntax is one of those decisions. It's worth learning from that and picking a clearer syntax for new languages, but it is not worth obsessing over its use in existing languages. > > Had no-one even glanced at a Pascal spec, if there was no working copy? > It would have transformed C type syntax. > > (ACTUALLY IT IS NOT TOO LATE. A secondary postfix deref op could have > been added. This could have been done 50 years ago, with the original > eventually deprecated. It /is/ too late - far, far too late. It would be a terrible idea to add a new postfix dereference operator to give two different operators with no benefit other than very occasionally reducing the need for parentheses. If "*p" really bothers you, write "p[0]" instead (in expressions, not type declarations). > > But this is a common theme of mine whether I perceive a problem that > people grudgingly admit might not be idea. But nothing was ever done to > fix it even after decades.) > What is the common theme? You pick something that lots of people consider as "it's maybe uglier than it need be, but it works fine in practice" and pretend that you alone discovered the issue? Then you go completely haywire about how terrible and unbelievable it is, call the C designers idiots and claim to be a genius because your irrelevant language does something different? Then comes the paranoia, and claims that no one will "admit there is a problem", and the absurd insistence that we all "do something about it". Eventually the thread dies away, until you bring up the same shit half a year later. For years, and years, and years. Is that the common theme you are talking about?
Re: Taming The Switch-Statement
Author: David Brown
Date: Tue, 20 Oct 2026 15:32
Date: Tue, 20 Oct 2026 15:32
32 lines
3140 bytes
3140 bytes
On 20/10/2026 16:56, Janis Papanagnou wrote: > On 2026-10-20 10:25, David Brown wrote: >> On 19/10/2026 23:27, Janis Papanagnou wrote: >>> On 2026-10-19 21:35, Michael S wrote: >>>> [...] >>> >>> I'm sorry, these are (AFAICT) common terms, and I thought obvious. >> >> I am afraid your terminology is further from common use than you thought. > > I'm afraid you are wrong here; in several ways. I'll expand below. You don't need to be defensive here - I am trying to help you see /why/ your terms might not have been the best choices. It is not criticism of your post, just advice on your terminology so that it does not detract from understanding the content. (It is already clear that they were not good choices - Michael has long experience in software development of many types, and if they were not obvious to him in the context of your posts, they were not good terms to use.) You post a lot of interesting things. You made a post with unnecessary convoluted terminology that distracted from the content of your post, perhaps based on the particular usage of particular terms in the particular computer science courses you took. So my apologies for trying to be helpful! (And do look up "monads" and "monadic operations" - they are all the rage in many programming languages these days.)
Re: Taming The Switch-Statement
Author: Dan Cross
Date: Tue, 20 Oct 2026 19:24
Date: Tue, 20 Oct 2026 19:24
550 lines
19665 bytes
19665 bytes
In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com> wrote:
>On 20/10/2026 09:01, David Brown wrote:
>> On 19/10/2026 23:28, bart wrote:
>
>>> (Funny that when I suggest that nested loop breaks are uncommon,
>>> everyone says I'm wrong! Some even write 200-line made-up examples to
>>> prove their point.)
>>
>> I don't remember "everyone" saying you were wrong to say that nested
>> loop breaks are uncommon - in fact, I don't remember /anyone/ saying
>> that was wrong.
>
>(There was a LOT of antipathy towards my idea to fix the common case of
>'loop-break' clashing with 'switch-break', BECAUSE it did not fix the
>problem of nested loop-break, which is uncommon, even though that wasn't
>the aim.)
Those are two different things. No one disagrees with you that
"nested break from a switch inside of a loop" is relatively more
common than other variants.
Using that as an excuse not to provide a more general mechanism
because you already have a proposal for the specific case is
what I and others took you to task for. I find this ironic,
since you rail against things in C that you do not like, citing
the most ridiculous examples you can think of that do not show
up in actual programs, yet for something where it is pointed out
to you that your solution does not generalize, you claim that it
does not need to because ... the general case rarely shows up in
a real program.
>>> There is no reason to abstract away that function pointer type.
>>>
>>> You probably do so in C /because/ the type involves * () and [] but
>>> have somehow persuaded yourself that it just better that way.
>>
>> Do you hear that whooshing noise? It is the sound of the point flying
>> far above your head.
>>
>> Here is an example of some sensible function typedefs, all from third-
>> party code (so not my "peculiar" style)
>>
>> typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
>>
>> TimerHandle_t xTimerCreate( const char * const pcTimerName,
>> TickType_t xTimerPeriodInTicks,
>> UBaseType_t uxAutoReload,
>> void * pvTimerID,
>> TimerCallbackFunction_t pxCallbackFunction );
>>
>> typedef void (*lwip_thread_fn)(void *arg);
>> typedef void (*tcpip_init_done_fn)(void *arg);
>> typedef void (*tcpip_callback_fn)(void *ctx);
>> typedef void (* sys_timeout_handler)(void *arg);
>> typedef void (*dns_found_callback)(const char *name,
>> const ip_addr_t *ipaddr, void *callback_arg);
>
>This is the kind of C I find hard to read. There are lots of typedefs
>but few uses of those typedefs that I can see, so I don't know how much
>difference they make.
You again missed the entire point. You may not see many uses
of them, but as David says, the `typedef`s give you
domain-specific *names* understandable to the programmer: a
programmer can see the `sys_timeout_handler` type instantly know
that this has a different function than the,
`tcpip_callback_fn`, despite the having the same type.
The other point is that the ridiculous examples you make up to
illustrate your distaste for C declaration syntax basically do
not appear in real programs.
>[snip]
>I've left in the regular parameter names, even though C doesn't need
>them, but they are quite heavy - you don't really need those
>Hungarian-style prefixes.)
>
>Well, I guess this buys you one thing: the parameter name for the last
>parameter is to the right of its type, rather than be inside it. But a C
>expert should not be fazed by that.
>
>Here is the same function as I might write it in an alternative syntax.
>
>I've kept the same names, but changed case-style and removed prefixes
>and suffixes. I've capitalised user-type names:
>
>func TimerCreate( # (retain case if FFI import)
> ichar timername,
> Ticktype timerperiodinticks,
> Ubasetype autoreload,
> ref void timerid,
> ref proc(Timerhandle) callbackfn)
>
>In this form, it's hard to see what benefit a typedef would give for
>that last parameter; it is simple enough.
What is your point? Do you have one? If you don't want to use
C, don't use C.
There are plenty of languages that can do this kind of thing
that are not C and have syntax and semantics closer to what you
seem to want. Here's an example in Rust:
pub trait TimerHandle { ... }
fn CreateTimer<T>(
timer_name: &str,
period: std::time::Duration,
auto_reload: bool,
timer_id: T,
handler: fn(&dyn TimerHandle),
) -> Result<Timer<T>, TimerError>
I didn't know what an `UBaseType_t` is, and while "autoreload"
sounded pretty intuitive, I wasn't sure about the semantics, so
I looked it up (the example comes from `FreeRTOS`). In this
context, it is a boolean saying whether the timer should repeat
with the given periodicity, or whether it is a one-shot.
The timer_id is opaque to the timer, and it looks like it's used
to facilitating the handler accessing timer-specific data. In
C, passing it as a `void *` is used as a way to get a poor-man's
overloading. But Rust has generics, I just made it generic over
some type T.
If I were writing this from scratch in Rust, a language that has
generics, closures, and so sum types, I'd do the whole thing
differently; see the end for an example.
But I digress. The point here is, Bart, that alternatives exist
if you don't like C. You don't have to keep posting, over and
over again, in comp.lang.c of all places, about how oh so
terribly awful C is. If you don't want to program in C, simply
don't program in C.
>> Ask yourself why the typedefs are used. Look at the /names/. Those
>> last four are all from the same network stack library, and are all
>> typedefs for "void (*)(void*)".
>
>Until you mentioned it, I hadn't noticed. So typedef has done a good job
>of hiding that useful fact! But looking more closely, it is the first
>four of the last five.
>
>Let's take one:
>
> typedef void (*lwip_thread_fn)(void *arg);
>
>That 'arg' is not much use for a start (other than being a hint that
>this particular (...) is where the parameters go).
>
>So, maybe this is used like this:
>
> void F(lwip_thread_fn lwip_thread_callback);
I have no idea what you're trying to say here. The obvious (and
honestly, excusable) syntax error aside, what is F? It's a
function that, what, takes two function pointers?
The type defined by `lwip_thread_fn` is a pointer to a function
that takes a void pointer (`void *`) as its sole arugment, and
returns `void` (that is, has no meaningful return value).
Intuitively, the name implies that this is the function run as
some thread, so we'd pass it to a thread creation function. The
usual shape of those things is to give them a pointer to some
function to run in the new thread, and a pointer to some
arguments to be passed to that function. For example:
void
whatever(void *argp)
{
struct Args *args = argp;
while (keep_running()) {
// Do the thing the thread is supposed to do.
}
thread_exit(SUCCESS);
}
thread_t *
start_the_whatever_thread(void)
{
struct Args *args = malloc(sizeof(*args));
if (args == NULL) abort();
memset(args, 0, sizeof(*args));
args->whatever = something();
// etc...
thread_t *thr = thread_create(whatever, args);
if (thr == NULL) abort();
return thr;
}
Something could start this as:
thread_t *whatever_id = start_the_whatever_thread();
At some point later, if you want to wait for the thread to
exit, you'd run:
(void)thread_join(whatever_id);
Note this is decently complex behavior, but it's actually quite
intuitive from the name and the type.
>Here you have two identifiers imparting the sort kind of information; a
>tautology.
That's not what a tautology is.
>If that function pointer pattern is common, or recurs in a suite of
>functions, I might also have used a typedef, but with a common name.
Then you loose the domain specificity; you can't tell from the
name whether you need an LwIP thread, or a callback, or a
something run in a different thread, or just a plain 'ol
function you want to apply to run every now and again for a side
effect.
>Then only one would be needed, say:
>
> typedef void (*stack_callbackfn)(void);
>
>I might have done the same in that alternate syntax as it would start to
>get cluttery: 'ref proc(ref void)', but also in order to define that
>common pattern in one place.
I dunno. Sounds like you have no idea what the code that David
posted is meant to do. But that's a "you" problem.
>>> Note that 'pcl' in my example /is/ a typedef; here it makes sense as
>>> it is used in 100s of places. This function pointer occurs in only one
>>> place.
>>
>> I'm sorry, I had mistaken you for a programmer who wanted to write good,
>> clear programs. Naming things is not a shortcut to save keypresses.
>
>Isn't that one of the main uses of typedefs? So as to give a handy,
>'euphonious' one-token alias to an elaborate typedef.
>
>It also allows you to change the type in one place without having to
>update hundreds of instances.
>
>It also allows the type to be opaque.
The point is that the name you chose is meaningless to anyone
other than you. What's a PCL? Phase Control Line? Printer
Command Language? Photon Compressor Loop?
>Saving keypresses is bonus benefit, but if it is shorter, then it can
>also help readability as other critical elements are not overshadowed.
>
>So I'm not sure what objection you have to this particular use of it.
Have you ever written a large program that was maintained by
anyone other than yourself?
>Here is the one place I do remember using typedef for a function pointer
>(from an old project, not in C):
>
> type fnptr = ref proc
>
> repeat
> (fnptr(pcptr^))^()
> until stopped
>
>It's used as a cast, but reason I have it is because with simple cast
>syntax, which is 'T(X)', the meaning without it would be ambiguous (a
>grammar issue that I might fix one day).
>
>Rather than fallback to standard cast syntax (which is 'cast(X, T)'),
>this was tidier.
I can only guess at what this may mean. Hazarding a guess,
`pcptr` is a "pointer to a program counter", which is a
reference type to some type that represents some executable
memory location in the program. You then have a loop that runs
until "stopped" is true where you indirect the program counter
pointer, cast it to a pointer to a function, and then invoke
the function, right? One presumes you have the, "PC Pointer"
because it changes over time, otherwise, you'd just give
whatever it points to a name and call it.
More generally, I fail to see what this is trying to
demonstrate. If it's to show some sort of imagined superiority
over C, I don't see it; that's sort of thing is easy enough to
write:
typedef void (*fnptr)(void);
// Assume uintptr_t *pcptr is declared somewhere.
do {
((fnptr)*pcptr)();
} while (!stopped);
E.g.,
```
term% cat b.c
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
static void first(void);
typedef void (*fnptr)(void);
bool stopped = false;
uintptr_t pc = (uintptr_t)first;
uintptr_t *pcptr = &pc;
void
done(void)
{
printf("done\n");
stopped = true;
}
void
second(void)
{
printf("second\n");
*pcptr = (uintptr_t)done;
}
void
first(void)
{
printf("first\n");
*pcptr = (uintptr_t)second;
}
void
run(void)
{
do {
((fnptr)*pcptr)();
} while (!stopped);
}
int
main(void)
{
run();
return 0;
}
term% gcc-16 -std=c11 -pedantic -o b b.c
term% ./b
first
second
done
term%
```
>>> BTW what name would be given to such a function pointer type?
>
>> I have no idea what your code is supposed to do,
>
>It's a table of function pointers! All sharing the same signature.
>
>That's pretty generic. Is it really that hard to guess? You don't need
>to know what they do, other than at some point they will be called as
>handlertable[i](arg).
That part is fine.
What's utterly mystifying is what you are trying to show, if
anything, by posting it. Is this supposed to prove some kind of
point? Your code is not _a priori_ easier to understand than
the equivalent C code; if anything, it is harder to understand
because of your poorly chosen names.
- Dan C.
-->Rust implementation of Timers, mentioned above<--
As mentioned above, if I were providing the FreeRTOS timers API
in an alternative language, I'd write it differently from the
start. In particular, I'd use an enumeration to describe the
behavior with respect to repeating, and I'd use a closure to
obviate the need for the opaque id. Something that isn't easy
to express in the original API is a type of repeating timer that
waits for the initial period, and then repeats with some
different period.
Something like this:
```rust
pub mod timer {
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
/// Errors that may occur when working with timers.
#[derive(Clone, Copy, Debug)]
pub enum Error {
Running,
CantStop,
WontStop,
}
/// Describes the kind of a timer, as defined by its
/// periodicity.
///
/// A timer can either be a `OneShot` timer, which fires
/// once, after its timeout expires, or it may be a Repeating
/// timer, which will automatically reset after its handler
/// is run and continue firing at the rate defined by the
/// initial timeout, or it can be a periodic timer, that
/// will fire the first time at the initial timeout, and
/// then repeatedly a potentially different timeout. This
/// use case can be simulated by a OneShot timer that
/// creates a repeating Timer, but
///
/// Once started, Repeating and Periodic timers continue
/// firing until explicitly stopped.
#[derive(Clone, Copy, Debug)]
pub enum Kind {
OneShot,
Repeating,
Periodic(Duration),
}
/// A named timer, that is handled by the given callback.
pub struct Timer<'a, F> {
pub name: &'a str,
pub kind: Kind,
pub timeout: Duration,
callback: F,
running: AtomicBool,
// Whatever other innards...
// ...
}
/// A read-only "view" into the timer.
pub trait TimerView {
fn name(&self) -> &str;
fn kind(&self) -> Kind;
fn timeout(&self) -> Duration;
}
impl<'a, F: Fn(&dyn TimerView)> Timer<'a, F> {
/// Creates a new named timer of the given kind with an
/// initial timeout. When the timeout expires, it will
/// automatically invoke the given handler.
pub fn new(
name: &'a str,
timeout: Duration,
kind: Kind,
callback: F,
) -> Timer<'a, F> {
let running = AtomicBool::new(false);
Self {
name,
kind,
callback,
timeout,
running,
}
}
/// Starts the timer.
pub fn start(&self) -> Result<(), Error> {
if self.running.swap(true, Ordering::AcqRel) {
return Err(Error::Running);
}
self.arm(self.timeout)?;
Ok(())
}
/// Stops the timer.
///
/// Note that this inherently races with the timer firing,
/// and a timer event that occurs while we are disabling
/// the timer may still invoke `fired` after this returns.
///
/// Callers are advised to determine definitively that
/// there are no events pending for this timer before
/// destroying the `Timer` object.
pub fn stop(&self) -> Result<(), Error> {
let was_running = self.running.swap(false, Ordering::AcqRel);
if !was_running {
return Err(Error::WontStop);
}
self.disarm();
Ok(())
}
// Automatically called when the timeout fires.
//
// # Safety
//
// Nothing may be mutably borrowing a reference to the
// Timer object when this is called.
pub(super) unsafe fn fired(&self) -> Result<(), Error> {
if !self.running.load(Ordering::Acquire) {
return Ok(());
}
(self.callback)(self);
match self.kind {
Kind::OneShot => Ok(()),
Kind::Repeating => self.arm(self.timeout),
Kind::Periodic(period) => self.arm(period),
}
}
// Arranges for `self.fired(self)` to be called when
// the given timeout expires.
fn arm(&self, timeout: Duration) -> Result<(), Error> {
// Does whatever one does here to actually arm the
// timer (e.g., calls a HAL to actually program a
// physical timer to interrupt after the amount of
// time specified by `Duration`, for example).
// ...
Ok(())
}
// Disables an armed timer, so that it does not fire
// after this returns.
fn disarm(&self) -> Result<(), Error> {
// whatever one does here to disarm an active timer
// ...
Ok(())
}
}
impl<F> TimerView for Timer<'_, F> {
fn name(&self) -> &str { self.name }
fn kind(&self) -> Kind { self.kind }
fn timeout(&self) -> Duration { self.timeout }
}
}
```
One might use this with something like,
```
let value = 42;
let cb = move |timer: &dyn timer::TimerView| {
println!(
"Timer '{}' fired; value is {} and duration was {} ms",
timer.name(),
value,
timer.timeout().as_millis()
);
};
let timeout = std::time::Duration::from_millis(100);
let timer = timer::Timer::new("timer", timeout, timer::Kind::OneShot, &cb);
timer.start().expect("Timer started");
//... at some point the timer fires and prints,
// 'Timer 'timer1' fired; value is 42 and duration was 100 ms'
}
```
Re: Taming The Switch-Statement
Author: bart
Date: Tue, 20 Oct 2026 20:07
Date: Tue, 20 Oct 2026 20:07
168 lines
7239 bytes
7239 bytes
On 20/10/2026 16:02, David Brown wrote:
> On 20/10/2026 16:11, bart wrote:
>
>> The other was C. There, several choices were made:
>>
>> * To start with that Fortran style except that [] are used
>>
>> * To decree that that 'A[20]' syntax is supposed to match indexing of
>> A as it might appear in an expression
>>
>> * To introduce "*" as a prefix dereference operator in expressions ...
>>
>> * ... which then means that a prefix "*" appears in the declaration too
>>
>> * A further complication was to allow function pointers within that a
>> declaration list
>
> I don't see a problem with that. If you need to declare a function
> pointer, you need to declare it in a declaration list.
>
> To me, the big disadvantage of C's declaration syntax is that it lets
> you declare things of different (but related) types in the same
> declaration.
Yes, but that doesn't bite so much because it is uncommon.
> or, more common and therefore worse :
>
> int * a, b;
(See below.)
>> * Yet one more which came later was to add 'const', where placement now
>> gets confusing
>
> Some people do find it hard to understand the difference between :
>
> const int * p;
> int * const q;
> const int * const r;
>
> I note that this is despite the clear left-to-right nature of "const" here.
I was going to say it was right-to-left, but it can be considered both
and thus not clear:
const int const * const p;
1 2 3
const 1 applies to the basetype to its right.
const 2 applies to the basetype to its left.
(Both also can be in the middle with compound types like 'long long'!)
const 3 is tricky: I think it applies to the * to its left, since it
says that the pointer value itself is const. But 'p' has type 'pointer
to', so it could apply to that directly.
What about this however:
int * const * p;
1 2 3
I think here, const 2 applies to * 1, which is to it's left, and can't
apply to 'p' as that is the other side of the * 3.
Fair to say that is a complete mess, and it is error prone.
With a LTR syntax that a postfix deref would achieve, 'const' would
always be written immediately to the left of any * modifiers. (It is
meaningless for arrays and functions.)
It is never applied directly to a variable name.
For base types, it can be applied on the left, but C would still allow
it on the right or in the middle, or all three with duplicates.
That means there would be an ambiguity here where there is no identifier
between 'int' and 'const':
(const int const *)
For such reasons I would restrict base type const to be only on the left.)
> Complicated types are a minority.
I've showed even simple types or trying to use 'const' get becomes
confusing.
>> So, PARENTHESES HAVE BEEN ELIMINATED for purpose of disambiguating
>> array/pointer and pointer/array, both within expressions and within
>> type-declarations.
>
> Agreed.
>
> But does that make a significant difference? I don't think so.
It would make a HUGE difference:
(1) It helps to fix that confusion above
(2) You don't need parentheses so no need to remember if you want
(*A)[] or *A[]. Those will disappear from expressions too; less
clutter all round.
(3) It simplifies indexing of pointer-to-array from (*A)[i] to A*[i], so
that actual array pointers, which are more type-safe, could start to
appear more in C rather than the current T* idiom
(4) For pointers to structs, these are the patterns:
prefix * With -> With postfix *
(*P).m P->m P*.m
(**P).m (*P)->m P**.m
(***P).m (**P)->m P***.m
Which column looks the tidiest?
(5) With prefix *, a pointer type looks like 'T*'; notice the * is on
the right, not left! With postfix *, it would all be consistent. You
also wouldn't have 'T*A'; that would be an error (T* only happens
when there is no name)
(6) Your 'int * a, b' example would become:
int a *, b;
Much easier, even with that space, to see that '*' does not belong to
the base type but is a modifier for that variable.
It doesn't fix everything, so you'd still have this:
int p* = &a;
p* = a;
To fix this requires that all modifiers apply to the base type. But this
would be a massive change. The above is merely what happens when *
becomes postfix.
>> A mistake that could so easily have been avoid by choosing a different
>> precedence as shown above. Did none of the thousand people working at
>> Bell Labs (according to a comment in DC's follow-ip) spot this and say
>> anything?
>
> I suspect the folks at Bell Labs were too busy writing real code to be
> bothered by how confused you would be with artificially complex types.
So you agree the process was very different compared to that which lead
to Ada for example? Just a couple of guys left to do their own thing.
(Maybe they were respected enough that no one dared to offer any
constructive criticism, or if they did then it was dismissed. As happens
here.)
>>
>> (ACTUALLY IT IS NOT TOO LATE. A secondary postfix deref op could have
>> been added. This could have been done 50 years ago, with the original
>> eventually deprecated.
>
> It /is/ too late - far, far too late. It would be a terrible idea to
> add a new postfix dereference operator to give two different operators
> with no benefit other than very occasionally reducing the need for
> parentheses.
But a special operator P->m to do the same job as (*P).m was fine! The
new op would eliminate the need for ->.
Re: Taming The Switch-Statement
Author: bart
Date: Tue, 20 Oct 2026 20:30
Date: Tue, 20 Oct 2026 20:30
35 lines
2534 bytes
2534 bytes
On 20/10/2026 20:24, Dan Cross wrote: > In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com> wrote: > The point is that the name you chose is meaningless to anyone > other than you. What's a PCL? Phase Control Line? Printer > Command Language? Photon Compressor Loop? Within the context of that application then it would be clear. You're just being overly hostile. (Within the app, PCL is the name of a bytecode language, and 'pcl' is a reference to a specific instruction. Next time I'll just use T for such examples, since the type is not relevant to the point. Although that didn't stop you seizing upon my F function.) >> Here is the one place I do remember using typedef for a function pointer >> (from an old project, not in C): >> >> type fnptr = ref proc >> >> repeat >> (fnptr(pcptr^))^() >> until stopped > More generally, I fail to see what this is trying to > demonstrate. Not much. It is just a rare example of my using aliases for function pointers. Because I suggested such aliases are often unnecessary and partly used in C to get around the fiddly type syntax that would arise.
Re: Taming The Switch-Statement
Author: Michael S
Date: Tue, 20 Oct 2026 20:33
Date: Tue, 20 Oct 2026 20:33
198 lines
8719 bytes
8719 bytes
On Tue, 20 Oct 2026 15:11:35 +0100 bart <bc@freeuk.com> wrote: > On 20/10/2026 02:03, Waldek Hebisch wrote: > > bart <bc@freeuk.com> wrote: > >> > >> OK. But they HAD to create C? There were quite a few languages in > >> the early 70s too: like Pascal, Fortran, PL/I, Coral-66, plus of > >> course BCPL and B. So why a new one? > > > > You ignore fact that Ritche wanted reasonably fast code from > > very simple compiler. > > According to DC's quote from HOPL, it was also more fun to create a > new language. > > > > PL/I had most needed features. But PL/I was a big language, > > to run on small machine they would have to take tiny subset > > and then add extentions. Basicaly they would end up with a > > language which is very far from PL/I. > > There were PL/360 and PL/M, although those were more specific, more > 'machine-oriented' languages. (I implemented one for PDP10 but it was > a port of a systems language from a GEC machine.) > PL/M is approximately contemporary to C, most likely Ritchie had first compiler working few months before Kildall. But input language of the early C compilers was likely further away from what it evolved later than early PL/M to later its variant. C was self-hosted on minicomputer from the beginning. PL/M originally required more powerful and expensive host. Eventually PL/M host requirements were reduced below those of C, but it took couple of years. > Anyway, a more general subset could have been used. > I suppose that you wholeheartedly agree. I don't. I never found computer language design fun. > > > Similarly, BCPL was too complicated, B and C were simplifications > > and adaptations small machine. > > > > I think that Pascal was too late: nominally it was created earlier > > but I think that it was available to Bell Labs only after they > > did initial work leading to C. And Pascal shared problem of > > speed on small machines. Note that later UCSD Pascal which > > run on micros compiled to interpreted bytecode, which significantly > > reduced performance. > > It would not have been hard to use Pascal as a starting point for a > workable systems language. Wirth wouldn't have approved, but his > languages were too pure, too academic; some of us had things we > needed to get done! > > Here I mean adapting Pascal for a competing systems language. > Pascal without several extensions does not seem suitable for system programming. > In my hands some aspects would be simplified (eg. no nested > functions, no closures), thus making it easier to generate decent > code with a simple compiler. > But then, it's not Pascal. And still needs extensions. > > > > >> FORTRAN syntax looked nothing like C! Unless you mean the general > >> pattern of 'INTEGER A, B' which was shared by half of all > >> languages. > > > > I think more pattern of > > > > INTEGER A(20), B > > > > which has similar structure to C variable declarations. > > OK. That was typical for the time. But in Fortran it didn't get much > more complicated than that. Maybe 2D arrays and so on. > > > Of course, > > FORTRAN had no pointers (and structures or unions), so Ritche had > > to invent syntax for them. > > There were three languages from that era that I know had pointers or > references, and which allowed composing arbitrary types with arrays > and pointers, two of which were Algol68 and Pascal. > > Both used a 100% LTR form. > > The other was C. There, several choices were made: > > * To start with that Fortran style except that [] are used > > * To decree that that 'A[20]' syntax is supposed to match indexing of > A as it might appear in an expression > > * To introduce "*" as a prefix dereference operator in expressions ... > > * ... which then means that a prefix "*" appears in the declaration > too > > * A further complication was to allow function pointers within that a > declaration list > > * Yet one more which came later was to add 'const', where placement > now gets confusing > > But to stay with pointers, take this expression: > > *A[i] > > C precedence rules mean this is parsed as *(A[i]), which means that a > type written as 'T *A[N]' must be an array of pointers to T (I had to > think for a few seconds!). > > But suppose you wanted a pointer to array of T? The expression for > that would be: > > (*A)[i] > > And so the declaration has to be 'T (*A)[N]' too. > > So it is unfortunate that parentheses used to control precedence in > an expression now also have to appear in type declarations (where > they are often next to () used for parameter lists, for further > confusion). > > ============================================== > > So, what would have happened with a postfix deref op? (Ignore whether > '*' would still be a good choice.) My first example would be this: > > A*[i] > > Here, it would mean that A is dereferenced, then indexed; A must then > be a pointer to an array of T. > > But suppose we wanted the original array of pointers to T, where you > index first then dereference. That is written like this: > > A[i]* > > You simply swap the order of [] and *. > > So, PARENTHESES HAVE BEEN ELIMINATED for purpose of disambiguating > array/pointer and pointer/array, both within expressions and within > type-declarations. > > How about that? Further, most of the type-spec is now LTR; only the > base-type has to stay on the left. Access terms in expressions will > be fully LTR. > > > IMO C suffers because typedef was added late in the game and > > function prototypes are much later. Prototypes need types and > > to get it one needs "hole" in variable declaration. Where the > > hole should be is specified by the C syntax, but placement of > > hole is probably least clear aspect of declarations. > > I thought that 'hole' was where 'int A[10]' mean one thing in normal > declaration but another within a parameter list. > > > IMO C declaration syntax was a mistake, but as real life shows > > it was not a fatal mistake, people can adapt. > > A mistake that could so easily have been avoid by choosing a > different precedence as shown above. Did none of the thousand people > working at Bell Labs (according to a comment in DC's follow-ip) spot > this and say anything? > Methinks there were less than 100 people exposed to C before it became too late. May be, just 50. > Had no-one even glanced at a Pascal spec, if there was no working > copy? It would have transformed C type syntax. > > (ACTUALLY IT IS NOT TOO LATE. A secondary postfix deref op could have > been added. This could have been done 50 years ago, with the original > eventually deprecated. > > But this is a common theme of mine whether I perceive a problem that > people grudgingly admit might not be idea. But nothing was ever done > to fix it even after decades.) > It was. There are many new languages. Today, C sees little use outside of small to mid-sized mocrocontrollers and OS kernels. Most user-layer applications on general purpose computers are written in newer languages.
Re: Taming The Switch-Statement
Author: Dan Cross
Date: Tue, 20 Oct 2026 21:44
Date: Tue, 20 Oct 2026 21:44
49 lines
2708 bytes
2708 bytes
In article <11b8j17$3btus$1@dont-email.me>, bart <bc@freeuk.com> wrote: >On 20/10/2026 20:24, Dan Cross wrote: >> In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com> wrote: > >> The point is that the name you chose is meaningless to anyone >> other than you. What's a PCL? Phase Control Line? Printer >> Command Language? Photon Compressor Loop? > >Within the context of that application then it would be clear. You're >just being overly hostile. Not really. You are, I presume, posting that code to try and make some kind of point about how "readable" it is. But it's not readable unless you already know what it does. On the other hand, the code David posted _is_ readable, because it uses the language to encode domain-specific information into type names. >(Within the app, PCL is the name of a bytecode language, and 'pcl' is a >reference to a specific instruction. > >Next time I'll just use T for such examples, since the type is not >relevant to the point. Although that didn't stop you seizing upon my F >function.) You just don't get it. I suspect you have no idea what the `typedef`s David posted actually represent. >>> Here is the one place I do remember using typedef for a function pointer >>> (from an old project, not in C): >>> >>> type fnptr = ref proc >>> >>> repeat >>> (fnptr(pcptr^))^() >>> until stopped > >> More generally, I fail to see what this is trying to >> demonstrate. > >Not much. It is just a rare example of my using aliases for function >pointers. Because I suggested such aliases are often unnecessary and >partly used in C to get around the fiddly type syntax that would arise. Yeah, you really just don't get it. - Dan C.
Re: Taming The Switch-Statement
Author: bart
Date: Tue, 20 Oct 2026 22:43
Date: Tue, 20 Oct 2026 22:43
60 lines
3311 bytes
3311 bytes
On 20/10/2026 22:44, Dan Cross wrote:
> In article <11b8j17$3btus$1@dont-email.me>, bart <bc@freeuk.com> wrote:
>> On 20/10/2026 20:24, Dan Cross wrote:
>>> In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com> wrote:
>>
>>> The point is that the name you chose is meaningless to anyone
>>> other than you. What's a PCL? Phase Control Line? Printer
>>> Command Language? Photon Compressor Loop?
>>
>> Within the context of that application then it would be clear. You're
>> just being overly hostile.
>
> Not really. You are, I presume, posting that code to try and
> make some kind of point about how "readable" it is. But it's
> not readable unless you already know what it does.
What it does not relevant. This is simply defining an array of T. But
because T happens to be a function pointer, DB insists that an alias
must be created, and a new name invented.
Why? Probably because in C, the syntax for function pointers gets hairy.
> On the other hand, the code David posted _is_ readable, because
> it uses the language to encode domain-specific information into
> type names.
Maybe we should create aliases for function signatures more often then,
then we can encode that extra info.
So that instead of, for example:
void SomeFunc(int x, int y) {printf("%d %d\n", x, y);}
you do:
typedef void Take2Ints(int x, int y);
Take2Ints SomeFunc {printf("%d %d\n", x, y);}
If you have a suite of functions sharing the signature, then it might be
a good idea. But funnily enough, you never see this being done.
(I don't know if this is legal C; but it works fine with my compiler:
c:\m>type fred.c
#include <stdio.h>
typedef void Take2Ints(int x, int y);
Take2Ints SomeFunc{printf("%d %d\n", x, y);}
int main(void) { SomeFunc(10, 20); }
c:\m>bcc -r -q fred
10 20
)
> Yeah, you really just don't get it.
One of us doesn't get it.
Re: Taming The Switch-Statement
Author: bart
Date: Tue, 20 Oct 2026 23:01
Date: Tue, 20 Oct 2026 23:01
56 lines
3482 bytes
3482 bytes
On 20/10/2026 21:33, Michael S wrote: > On Tue, 20 Oct 2026 15:11:35 +0100 > bart <bc@freeuk.com> wrote: > I suppose that you wholeheartedly agree. I don't. I never found computer > language design fun. The fun part is afterwards when you use your very own language. Quite a way to get there though. > Methinks there were less than 100 people exposed to C before it became > too late. May be, just 50. Were you there? You seem confident of those figures! I've no idea what went on, myself; I can only speculate. > >> Had no-one even glanced at a Pascal spec, if there was no working >> copy? It would have transformed C type syntax. >> >> (ACTUALLY IT IS NOT TOO LATE. A secondary postfix deref op could have >> been added. This could have been done 50 years ago, with the original >> eventually deprecated. >> >> But this is a common theme of mine whether I perceive a problem that >> people grudgingly admit might not be idea. But nothing was ever done >> to fix it even after decades.) >> > > It was. There are many new languages. > Today, C sees little use outside of small to mid-sized mocrocontrollers > and OS kernels. > Most user-layer applications on general purpose computers are written > in newer languages. I still see C everywhere, for example in the APIs of libraries like SDL, STB, GTK, OpenGL, Raylib, GMP, plus the APIs for many Windows subsystems, plus Linux. It's also popular as a target language for compilers (when LLVM is too much). Amateur compiler writers also seem to love creating C or C subset compilers more than any other language (they perceive it as simpler than it really is). And many language projects are still written in C, or at bootstrapped with C. This is all desktop machines still. Of course many are also migrating to products like Rust, Go and Zig. For me, the fact that there's still an appetite for a language of this class is one reason I still persist with mine.
Re: Taming The Switch-Statement
Author: Tim Rentsch
Date: Tue, 20 Oct 2026 23:10
Date: Tue, 20 Oct 2026 23:10
134 lines
8161 bytes
8161 bytes
antispam@fricas.org (Waldek Hebisch) writes: > Tim Rentsch <tr.17687@z991.linuxsc.com> wrote: > >> antispam@fricas.org (Waldek Hebisch) writes: >> >>> Lawrence D?Oliveiro <ldo@nz.invalid> wrote: >>> >>>> On Tue, 13 Oct 2026 07:23:40 -0000 (UTC), Waldek Hebisch wrote: >>>> >>>>> So what those counts indicate: majority of loops is simple, that is >>>>> have no early exit. Vast majority of early exits is done via >>>>> 'return'. >>>> >>>> My experience in my own C code is quite the opposite. Lots of loops >>>> have exits in the middle, leading me to use forms like ?for (;;)?. I >>>> also try to avoid putting ?return? anywhere other than the end of a >>>> function, to make it easier to see the flow of control. >>> >>> Well, usually there is a lot of loops. Those with exit in the >>> middle are still significant. >>> >>> Concernig 'return', having it in place where all work inside function >>> is done help me to see flow control and avoids complications. In >>> case of search functions it means return from the middle of the loop. >>> IMO possible alternatives like flag variables or break and retrun >>> after loop are worse. >> >> I rarely use 'break' to exit a loop. Part of this is that I try to >> write standard loops so that they complete as part of the loop test >> (i.e., in while() or for() control expressions). That isn't the >> whole story though so let me talk about 'return'. > > I counted various constructs in a small suite of 2 programs (1306 > lines in 3 files). There are 4 breaks outside switches and 32 > loops in total. My gut feeling is that this proportion is > reasonable close to typical in my code. For comparison, there > are 67 functions and 70 'if'-s. Probably that is close to what I see for my own code, if we count 'return' out of a loop. >> Most of the functions I write have exactly one return, at the end of >> the function. I estimate this pattern accounts for around 85% of >> all functions, let's say plus or minus 5%. > > In code above about half of functions is 'void' and there are 34 > explicit returns (of which at least 2 are early returns). I almost never use void functions. I'm used to a functional style, and it's natural to return something in almost all cases. >> Sometimes functions have early returns for errors or exceptional >> conditions. > > Code above contains 16 occurences of 'exit(1)'. One of those is > in a macro that is used 10 times, so actually there are 25 places > which call 'exit(1)'. That is related to the programs being > simple utilities, there is no attempt to error recovery, on error > programs simply print error message and exit. okay. I don't use exit() often but I have no problem with that. >> Early returns are easily seen to lie outside the main >> body of function processing so they don't interfere with >> understanding what the rest of the function is doing or how it >> works. >> >> A fairly common sub-pattern are functions most of whose body is a >> switch() statement, with all of the switch() cases being a simple >> return. > > Code above has 2 switches, both are in parsing functions, where > cases either move to next state or signal error. Parsing functions > also open file and close it when finished and return data structure > with parsed info. In other kinds of code I might use switch() more often. Maybe I can try putting together a small application where switch() is more likely and see what I get. >> It does sometimes happen that a function will have a loop with a >> return in the middle, and also a return at the end for what to do if >> the loop terminates. To me having an in-loop return looks better >> than using an assignment and a break. >> >> A fairly rare but important pattern is what I might call vectoring >> or decomposition. Here the function body serves to distinguish and >> separate out different regimes of subprocessing. To continue >> processing in a particular regime, a return is used not to directly >> yield a value but rather to call a further function to handle that >> sub-domain. The benefit here is both to keep function bodies small >> and to allow re-use of commonly called sub-functions. >> >> Two aspects are important for having these different styles work >> together. One is that it's easy to distinguish the different kinds >> of patterns, and by far the most simple pattern is the most common. >> The other is to be sure to keep function bodies small. Keeping >> function bodies small goes a long way in making them easy to >> understand, which obviously is a key property in writing good code. >> Also keeping function bodies small effectively prevents mixing >> different styles in a single function, serving to reinforce point >> one. > > I think that in general my C code has similar characteristics. Yes it sounds that way. > But > let me note that while I have a lot of small functions, I also have > some which are bigger. I suspect that 10% or more of my code is > in functions that are bigger then 30 lines. Such functions > frequently have several variables and there is setup stage to > initialize things, actual processing and final part (cleanups, > possibly extraction of result). Stages are clearly sepatated > by their position inside function, OTOH are strongly coupled due > to use of variables. My feeling here is that in case of strongly > coupled code with no reusable parts keeping it inside single > function is more managable than trying to split it into smaller > functions. It's natural for me not to let functions get too large, which means more than about 60 lines of code. But beyond that wanting to write small functions doesn't mean only tiny functions. My "10% or more" function size may be a little smaller than yours, but not much smaller. Also I observe empirically an interesting property, which is that if we multiply the number of functions of size N by N, the result is roughly constant across the range of function sizes. So for example if there are three functions whose bodies have 50 lines then there are roughly 50 functions whose bodies have three lines. And that holds approximately across the whole range of function sizes (with a standard deviation about half the average). So there are lots of little functions but also functions of sizes in the 20s, 30s, 40s and 50s. Does that sound similar to your own code?
Re: Taming The Switch-Statement
Author: Keith Thompson
Date: Wed, 21 Oct 2026 00:05
Date: Wed, 21 Oct 2026 00:05
28 lines
2590 bytes
2590 bytes
David Brown <david.brown@hesbynett.no> writes:
[...]
> Without typedef's, that function signature would be something like :
>
> signed char dns_gethostbyname(const char *hostname, struct ip_addr
> *addr, void (*found)(const char *name, const struct ip_addr
> *ipaddr, void *callback_arg), void *callback_arg);
I might write that as:
signed char dns_gethostbyname(
const char *hostname,
struct ip_addr *addr,
void (*found)(
const char *name,
const struct ip_addr *ipaddr,
void *callback_arg
),
void *callback_arg
);
so the indentation and structure reflects the semantics. I find
that much clearer than your version. (I'm not commenting on the
merits of typedefs.)
--
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
Author: Dan Cross
Date: Wed, 21 Oct 2026 00:56
Date: Wed, 21 Oct 2026 00:56
81 lines
3654 bytes
3654 bytes
In article <11b8qqg$3ejlp$1@dont-email.me>, bart <bc@freeuk.com> wrote:
>On 20/10/2026 22:44, Dan Cross wrote:
>> In article <11b8j17$3btus$1@dont-email.me>, bart <bc@freeuk.com> wrote:
>>> On 20/10/2026 20:24, Dan Cross wrote:
>>>> In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com> wrote:
>>>
>>>> The point is that the name you chose is meaningless to anyone
>>>> other than you. What's a PCL? Phase Control Line? Printer
>>>> Command Language? Photon Compressor Loop?
>>>
>>> Within the context of that application then it would be clear. You're
>>> just being overly hostile.
>>
>> Not really. You are, I presume, posting that code to try and
>> make some kind of point about how "readable" it is. But it's
>> not readable unless you already know what it does.
>
>What it does not relevant. This is simply defining an array of T. But
>because T happens to be a function pointer, DB insists that an alias
>must be created, and a new name invented.
>
>Why? Probably because in C, the syntax for function pointers gets hairy.
I dunno; your syntax didn't seem any clearer to me.
>> On the other hand, the code David posted _is_ readable, because
>> it uses the language to encode domain-specific information into
>> type names.
>
>Maybe we should create aliases for function signatures more often then,
>then we can encode that extra info.
>
>So that instead of, for example:
>
> void SomeFunc(int x, int y) {printf("%d %d\n", x, y);}
>
>you do:
>
> typedef void Take2Ints(int x, int y);
>
> Take2Ints SomeFunc {printf("%d %d\n", x, y);}
>
>If you have a suite of functions sharing the signature, then it might be
>a good idea. But funnily enough, you never see this being done.
Yeah, you really don't get it.
You remind me of the guy at Google who objected to importing the
`std::` namespace in C++ into the default scope; "oh, so what;
we should all write ::std::whatever::foo<::std::blah>(...)?!" as
if finding the most stupidly extreme example was somehow a
useful technical argument. He also spent all his time on
mailing lists arguing about how everybody else Got It Wrong. He
got fired a few months later.
>(I don't know if this is legal C; but it works fine with my compiler:
>
> c:\m>type fred.c
> #include <stdio.h>
>
> typedef void Take2Ints(int x, int y);
>
> Take2Ints SomeFunc{printf("%d %d\n", x, y);}
>
> int main(void) { SomeFunc(10, 20); }
>
> c:\m>bcc -r -q fred
> 10 20
>)
Yeah, I gues running it through `gcc` is a really heavy lift.
<eyeroll>
>> Yeah, you really just don't get it.
>
>One of us doesn't get it.
I'm glad you can admit it.
- Dan C.
Re: Taming The Switch-Statement
Author: bart
Date: Wed, 21 Oct 2026 01:04
Date: Wed, 21 Oct 2026 01:04
95 lines
5241 bytes
5241 bytes
On 20/10/2026 13:58, David Brown wrote:
> On 20/10/2026 13:41, bart wrote:
> But let us take a concrete example. These network functions are from
> the LWIP network stack, which is designed to be used on small embedded
> systems that may not have any kind of OS - so it uses call-backs for
> asynchronous programming.
>
> An example API function is this :
>
> err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr,
> dns_found_callback found, void *callback_arg)
>
> The returned "err_t" can be "ERR_OK" (indicating the "hostname" is in
> the DNS cache and *addr is set to the IP), "ERR_ARG" for argument
> errors, or "ERR_INPROGRESS" to indicate that the stack is looking up the
> DNS name, and will call the callback when there is a final result or
> timeout.
>
>
> Without typedef's, that function signature would be something like :
>
> signed char dns_gethostbyname(const char *hostname, struct ip_addr
> *addr, void (*found)(const char *name, const struct ip_addr
> *ipaddr, void *callback_arg), void *callback_arg);
>
>
> Do you expect anyone to believe you if you claim this is easier to read
> than the real declaration using typedefs? I'll believe you if you say
> you find the original hard to read - but not if you claim the
> "untypedef'ed" version is clearer.
Neither are great. But let's first lay them out better:
err_t
dns_gethostbyname(
const char *hostname,
ip_addr_t *addr,
dns_found_callback found,
void *callback_arg
);
Here, one problem is that there are 3 types that I don't know and would
have to look up. The long version at least has all the info in one place:
signed char
dns_gethostbyname(
const char *hostname,
struct ip_addr *addr,
void (*found)(const char *name, const struct ip_addr *ipaddr,
void *callback_arg),
void *callback_arg
);
That signed char return is unusual; why not 'int'? (How would you even
print an 'err_t' value anyway)?
That 'ip_addr_t' turns out to be a struct. For those I would use
typedefs anyway; I rarely use struct tags and you have to invent an
identifier in either case.
Then we come to the function pointer, which is a quite a chunky one, but
let's work with it. Here, I would question whether you really need those
types in there, and especially those names.
Presumably you have a regular function of your own with the same
signature? You anyway never directly 'call' this parameter with
arguments; you just pass it the address of your handler.
Or do you use that typedef as documentation?
Where does the info come from anyway; does the library export a suitable
typedef? In that case you might as well use it. But if not, info must
come from elsewhere.
Anyway with some tweaks in place, using the struct typedef and using an
inline function pointer type, it would look like this:
signed char
dns_gethostbyname(
const char *hostname,
IP_addr *addr,
void (*found)(char*, IP_addr*, void *),
void *arg
);
In this form, it is not wildly different from your short version.
So I would look at other ways of tidying up before resorting to
extraneous typedefs.
But here, there may well be an extra reason to use a callback typedef; I
don't have the full details.
Re: Taming The Switch-Statement
Author: Keith Thompson
Date: Wed, 21 Oct 2026 01:23
Date: Wed, 21 Oct 2026 01:23
36 lines
3169 bytes
3169 bytes
David Brown <david.brown@hesbynett.no> writes:
> On 19/10/2026 23:27, Janis Papanagnou wrote:
[...]
>> * a b PN (Polish Notation)
>
> There is no term "Polish Notation" - except as occasionally used to
> mean /postfix/ as a short form of "Reverse Polish Notation". RPN was
> invented, or at least popularised, by the Polish logician Jan
> Łukasiewicz (I admit to looking that up on Wikipedia!). There is no
> "PN" opposite.
Yes, there most certainly is, and "* a b" is a good example of it.
https://en.wikipedia.org/wiki/Polish_notation
Jan Łukasiewicz invented what we now call Polish notation in 1924.
`+ 3 4` is an example (which yields 7). Lisp syntax is more or
less Polish notation with added parentheses. (I'm sure the phrase
"more or less" is doing a lot of work.)
Reverse Polish Notation, RPN, is very well known because it's
used by some calculators, particularly those made by HP. It's a
postfix notation. An example of RPN is `3 4 +` (which also yields 7).
I've never seen the term "Polish Notation", without "Reverse", used
to refer to postfix notation. PN is prefix; RPN is postfix.
I see that Janis already pointed out your error. I'm disappointed
that your followup did not acknowledge it. (I'm not commenting on the
rest of what Janis wrote.)
[...]
--
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
Author: bart
Date: Wed, 21 Oct 2026 01:39
Date: Wed, 21 Oct 2026 01:39
49 lines
3030 bytes
3030 bytes
On 21/10/2026 01:56, Dan Cross wrote: > In article <11b8qqg$3ejlp$1@dont-email.me>, bart <bc@freeuk.com> wrote: >> On 20/10/2026 22:44, Dan Cross wrote: >>> In article <11b8j17$3btus$1@dont-email.me>, bart <bc@freeuk.com> wrote: >>>> On 20/10/2026 20:24, Dan Cross wrote: >>>>> In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com> wrote: >>>> >>>>> The point is that the name you chose is meaningless to anyone >>>>> other than you. What's a PCL? Phase Control Line? Printer >>>>> Command Language? Photon Compressor Loop? >>>> >>>> Within the context of that application then it would be clear. You're >>>> just being overly hostile. >>> >>> Not really. You are, I presume, posting that code to try and >>> make some kind of point about how "readable" it is. But it's >>> not readable unless you already know what it does. >> >> What it does not relevant. This is simply defining an array of T. But >> because T happens to be a function pointer, DB insists that an alias >> must be created, and a new name invented. >> >> Why? Probably because in C, the syntax for function pointers gets hairy. > > I dunno; your syntax didn't seem any clearer to me. Yeah, the C is so much clearer. Of course, you would all lie through your teeth anyway before you'd admit mine might be simpler. I've just defined three entities: a variable, a function pointer, and a function, in both my syntax and in C's. Here are the first tokens of the C versions: int int int Can you guess which one is which yet? Here are the first three tokens in my syntax: int func ref Any easier? This is like PL Design 101.
Re: Taming The Switch-Statement
Author: Keith Thompson
Date: Wed, 21 Oct 2026 01:55
Date: Wed, 21 Oct 2026 01:55
14 lines
1771 bytes
1771 bytes
bart <bc@freeuk.com> writes:
[...]
> Yeah, the C is so much clearer. Of course, you would all lie through
> your teeth anyway before you'd admit mine might be simpler.
[...]
You preemptively accuse someone of being a liar, and then you wonder
why people are hostile to you.
Tone down the insults and hyperbole.
--
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
Author: Dan Cross
Date: Wed, 21 Oct 2026 01:56
Date: Wed, 21 Oct 2026 01:56
34 lines
2401 bytes
2401 bytes
In article <11b954e$3hjvi$1@dont-email.me>, bart <bc@freeuk.com> wrote: >On 21/10/2026 01:56, Dan Cross wrote: >> In article <11b8qqg$3ejlp$1@dont-email.me>, bart <bc@freeuk.com> wrote: >>> On 20/10/2026 22:44, Dan Cross wrote: >>>> In article <11b8j17$3btus$1@dont-email.me>, bart <bc@freeuk.com> wrote: >>>>> On 20/10/2026 20:24, Dan Cross wrote: >>>>>> In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com> wrote: >>>>> >>>>>> The point is that the name you chose is meaningless to anyone >>>>>> other than you. What's a PCL? Phase Control Line? Printer >>>>>> Command Language? Photon Compressor Loop? >>>>> >>>>> Within the context of that application then it would be clear. You're >>>>> just being overly hostile. >>>> >>>> Not really. You are, I presume, posting that code to try and >>>> make some kind of point about how "readable" it is. But it's >>>> not readable unless you already know what it does. >>> >>> What it does not relevant. This is simply defining an array of T. But >>> because T happens to be a function pointer, DB insists that an alias >>> must be created, and a new name invented. >>> >>> Why? Probably because in C, the syntax for function pointers gets hairy. >> >> I dunno; your syntax didn't seem any clearer to me. > >Yeah, the C is so much clearer. Of course, you would all lie through >your teeth anyway before you'd admit mine might be simpler. Oh, grow up. - Dan C.
Re: Taming The Switch-Statement
Author: Kenny McCormack
Date: Wed, 21 Oct 2026 07:22
Date: Wed, 21 Oct 2026 07:22
22 lines
1752 bytes
1752 bytes
In article <11b963d$3h5oi$2@kst.eternal-september.org>, Keith Thompson <Keith.S.Thompson+u@gmail.com> wrote: >bart <bc@freeuk.com> writes: >[...] >> Yeah, the C is so much clearer. Of course, you would all lie through >> your teeth anyway before you'd admit mine might be simpler. >[...] > >You preemptively accuse someone of being a liar, and then you wonder >why people are hostile to you. > >Tone down the insults and hyperbole. The Lord and Master has spoken. All must comply with His dictates. -- Just like Donald Trump today, Jesus Christ had a Messiah complex. And, in fact, the similarities between the two figures are quite striking. For example, both have a ragtag band of followers, whose faith cannot be shaken.
Re: Taming The Switch-Statement
Author: David Brown
Date: Wed, 21 Oct 2026 09:20
Date: Wed, 21 Oct 2026 09:20
339 lines
13899 bytes
13899 bytes
On 20/10/2026 22:07, bart wrote: > On 20/10/2026 16:02, David Brown wrote: >> On 20/10/2026 16:11, bart wrote: >> >>> The other was C. There, several choices were made: >>> >>> * To start with that Fortran style except that [] are used >>> >>> * To decree that that 'A[20]' syntax is supposed to match indexing of >>> A as it might appear in an expression >>> >>> * To introduce "*" as a prefix dereference operator in expressions ... >>> >>> * ... which then means that a prefix "*" appears in the declaration too >>> >>> * A further complication was to allow function pointers within that a >>> declaration list >> >> I don't see a problem with that. If you need to declare a function >> pointer, you need to declare it in a declaration list. >> >> To me, the big disadvantage of C's declaration syntax is that it lets >> you declare things of different (but related) types in the same >> declaration. > > Yes, but that doesn't bite so much because it is uncommon. > Unfortunately not - but it is uncommon to mix objects and function declarations, or objects of wildly different real types. >> or, more common and therefore worse : >> >> int * a, b; > > (See below.) > >>> * Yet one more which came later was to add 'const', where placement now >>> gets confusing >> >> Some people do find it hard to understand the difference between : >> >> const int * p; >> int * const q; >> const int * const r; >> >> I note that this is despite the clear left-to-right nature of "const" >> here. > I was going to say it was right-to-left, but it can be considered both > and thus not clear: > > const int const * const p; > 1 2 3 > > const 1 applies to the basetype to its right. > const 2 applies to the basetype to its left. These are redundant - they do the same thing. (I'd have preferred if the ordering rules were strict - allowing only "const int" or "int const" - but at least people are usually consistent in their style.) > > (Both also can be in the middle with compound types like 'long long'!) > > const 3 is tricky: I think it applies to the * to its left, since it > says that the pointer value itself is const. But 'p' has type 'pointer > to', so it could apply to that directly. Yes - it is "p" that is const, not the "*". > > What about this however: > > int * const * p; > > 1 2 3 > > I think here, const 2 applies to * 1, which is to it's left, and can't > apply to 'p' as that is the other side of the * 3. *p is of type "int * const" - thus you can use "*p" to access a pointer-to-int, but you can't use *p to change that pointer-to-int. Fortunately, such types are rare. > > Fair to say that is a complete mess, and it is error prone. No, it is not at all fair to say that. It is fair to say that a different way of writing types might make it easier to understand - but that's a /long/ way from saying it is "a complete mess". And you can't call it "error prone" unless you know that people regularly use such declarations, and often have bugs in their code as a result of doing so incorrectly. I think that is an unrealistic claim. I appreciate that it can be difficult to see exactly what that type means, unless you use such a construct regularly - but there is no benefit in wild exaggeration. And I don't think /any/ alternative syntax would make it easy to understand what that type really is, what it can do and what it cannot do, or why you might want it. > > With a LTR syntax that a postfix deref would achieve, 'const' would > always be written immediately to the left of any * modifiers. (It is > meaningless for arrays and functions.) You can write this in C++ : // This bit is only needed once template <typename T> using ptr = T *; // p is a pointer to a const pointer to an int ptr<const ptr<int>> p; That's LTR syntax. Sure, it also has < > parentheses, but that's a minor point since the ordering of the components is what apparently matters so much. Or you can write : typedef int * p_int; const p_int * p; Thus p is a pointer to a "const p_int", where a "p_int" is a pointer to an int. These are different ways to write the same type, including one that is LTR, and the main hinder to understanding remains the same - what is the type for? > > It is never applied directly to a variable name. > > For base types, it can be applied on the left, but C would still allow > it on the right or in the middle, or all three with duplicates. What do you mean "base types" ? Do you mean that C lets you write const long int a; long const int a; const int long a; int const long a; long int const a; int long const a; ? If that's your complaint, then I agree with that one - I would be happier if C had allowed only "const long int;" here. But I think most programmers are consistent in the style they use (though some prefer "east const"). > > That means there would be an ambiguity here where there is no identifier > between 'int' and 'const': > > (const int const *) > > For such reasons I would restrict base type const to be only on the left.) >> Complicated types are a minority. > > I've showed even simple types or trying to use 'const' get becomes > confusing. No, you haven't. You have shown that /you/ claim to be confused by types with "const". Most C programmers, once they are used to the language, do not find it confusing in common and simple types. You do not get to invent meaningless complicated types, claim that you don't understand them, and use that as evidence that C's declaration syntax is "a complete mess". At best, all you can show is that for complex types, C's syntax can require more thought to write or understand than some alternative syntaxes might. But we've all known that for decades. > >>> So, PARENTHESES HAVE BEEN ELIMINATED for purpose of disambiguating >>> array/pointer and pointer/array, both within expressions and within >>> type-declarations. >> >> Agreed. >> >> But does that make a significant difference? I don't think so. > > It would make a HUGE difference: Your points below are all true, but IMHO all very minor, and do not add up to anything much. They might be enough to tip the balance when developing a new language where you are trying to decide whether your dereference operator should be prefix or postfix, but they are not enough to cause any concern in a language that has chosen prefix. > > (1) It helps to fix that confusion above Your invented confusion. > > (2) You don't need parentheses so no need to remember if you want > (*A)[] or *A[]. Those will disappear from expressions too; less > clutter all round. That doesn't matter in practice. > > (3) It simplifies indexing of pointer-to-array from (*A)[i] to A*[i], so > that actual array pointers, which are more type-safe, could start to > appear more in C rather than the current T* idiom I don't see that as significant. I do agree that the decay of expressions using array types into pointer types is a source of error in C code - though I do not think it is as bad as you do. I would have been happier if arrays were value types and the expressions did not decay to pointer expressions without manual intervention (like taking the address of the first element). In my C++ code, I make a lot of use of std::array<> types for that purpose - in my C code, it is not uncommon for me to have arrays wrapped in a struct. But I just don't see pointer-to-array expressions to be common enough for the difference you describe to be important. > > (4) For pointers to structs, these are the patterns: > > prefix * With -> With postfix * > > (*P).m P->m P*.m > (**P).m (*P)->m P**.m > (***P).m (**P)->m P***.m > > Which column looks the tidiest? Far and away the most common - by orders of magnitude - are pointers to structs. "p->m" looks fine to me, and I prefer it to "p*.m". A pointer to a pointer to a struct is rare enough that it is a good thing for the syntax to stand out - with a postfix dereference, I'd probably still use parentheses and write "(p*)->m". > > (5) With prefix *, a pointer type looks like 'T*'; notice the * is on > the right, not left! With postfix *, it would all be consistent. You > also wouldn't have 'T*A'; that would be an error (T* only happens > when there is no name) The C declaration syntax is "declaration follows use". If "*" were a postfix operator, then the declaration of a pointer-to-int would become: int p*; while the type of p would be "int *". So you would still have an inconsistency there, unless you also changed the way C has its declarations. > > (6) Your 'int * a, b' example would become: > > int a *, b; > > Much easier, even with that space, to see that '*' does not belong to > the base type but is a modifier for that variable. It's still bad. I don't think finding a way to make it easier to write bad code is a good idea. > > It doesn't fix everything, so you'd still have this: > > int p* = &a; > p* = a; > > To fix this requires that all modifiers apply to the base type. But this > would be a massive change. The above is merely what happens when * > becomes postfix. So basically, the suggestion would change some very minor things - mostly in subjective ways - and not actually do anything for aspects of the language where there is more of a consensus that C is sub-optimal. And for this, you would want a fundamental change to one of the most used operators in all C code! > >>> A mistake that could so easily have been avoid by choosing a >>> different precedence as shown above. Did none of the thousand people >>> working at Bell Labs (according to a comment in DC's follow-ip) spot >>> this and say anything? >> >> I suspect the folks at Bell Labs were too busy writing real code to be >> bothered by how confused you would be with artificially complex types. > > So you agree the process was very different compared to that which lead > to Ada for example? Just a couple of guys left to do their own thing. I don't see how you reach that conclusion from what I wrote. It is, however, true that C was designed by a small number of people working closely together, rather than a large committee-based design process involving lots of people. > > (Maybe they were respected enough that no one dared to offer any > constructive criticism, or if they did then it was dismissed. As happens > here.) I have no insight into the culture at Bell Labs at the time, but that sounds extraordinarily unlikely. Feel free to offer some constructive criticism some time, and we will see if it is dismissed. Note that "constructive criticism" involves more than "It's C, and I hate everything about C because it is connected to *nix, and I hate everything about *nix because it is connected to C". And even if you occasionally have a valid criticism about C, it is not "constructive" criticism because we did not design the language, and we do not dictate how it could be changed or how it is used. > >>> >>> (ACTUALLY IT IS NOT TOO LATE. A secondary postfix deref op could have >>> been added. This could have been done 50 years ago, with the original >>> eventually deprecated. >> >> It /is/ too late - far, far too late. It would be a terrible idea to >> add a new postfix dereference operator to give two different operators >> with no benefit other than very occasionally reducing the need for >> parentheses. > > But a special operator P->m to do the same job as (*P).m was fine! The > new op would eliminate the need for ->. > The -> operator was added to C in 1972 ! It is not new - it has always been part of the language beyond its early prototype versions.
Re: Taming The Switch-Statement
Author: David Brown
Date: Wed, 21 Oct 2026 10:45
Date: Wed, 21 Oct 2026 10:45
32 lines
2967 bytes
2967 bytes
On 21/10/2026 02:05, Keith Thompson wrote: > David Brown <david.brown@hesbynett.no> writes: > [...] >> Without typedef's, that function signature would be something like : >> >> signed char dns_gethostbyname(const char *hostname, struct ip_addr >> *addr, void (*found)(const char *name, const struct ip_addr >> *ipaddr, void *callback_arg), void *callback_arg); > > I might write that as: > > signed char dns_gethostbyname( > const char *hostname, > struct ip_addr *addr, > void (*found)( > const char *name, > const struct ip_addr *ipaddr, > void *callback_arg > ), > void *callback_arg > ); > > so the indentation and structure reflects the semantics. I find > that much clearer than your version. (I'm not commenting on the > merits of typedefs.) > Certainly the indentation makes the unpleasant non-typedef'ed version clearer. And /if/ I had to write that function signature without typedefs, I would structure it like you had - but I can't think of any reason I would ever have to do so.
Re: Taming The Switch-Statement
Author: David Brown
Date: Wed, 21 Oct 2026 11:21
Date: Wed, 21 Oct 2026 11:21
173 lines
8947 bytes
8947 bytes
On 21/10/2026 03:04, bart wrote: > On 20/10/2026 13:58, David Brown wrote: >> On 20/10/2026 13:41, bart wrote: > >> But let us take a concrete example. These network functions are from >> the LWIP network stack, which is designed to be used on small embedded >> systems that may not have any kind of OS - so it uses call-backs for >> asynchronous programming. >> >> An example API function is this : >> >> err_t dns_gethostbyname(const char *hostname, ip_addr_t *addr, >> dns_found_callback found, void *callback_arg) >> >> The returned "err_t" can be "ERR_OK" (indicating the "hostname" is in >> the DNS cache and *addr is set to the IP), "ERR_ARG" for argument >> errors, or "ERR_INPROGRESS" to indicate that the stack is looking up >> the DNS name, and will call the callback when there is a final result >> or timeout. >> >> >> Without typedef's, that function signature would be something like : >> >> signed char dns_gethostbyname(const char *hostname, struct ip_addr >> *addr, void (*found)(const char *name, const struct ip_addr >> *ipaddr, void *callback_arg), void *callback_arg); >> >> >> Do you expect anyone to believe you if you claim this is easier to >> read than the real declaration using typedefs? I'll believe you if >> you say you find the original hard to read - but not if you claim the >> "untypedef'ed" version is clearer. > > Neither are great. But let's first lay them out better: > > err_t > dns_gethostbyname( > const char *hostname, > ip_addr_t *addr, > dns_found_callback found, > void *callback_arg > ); OK. I'd not write it that way, and I don't think it is better, but that's a subjective opinion. (As a note on layout, the original code is not as line-length restricted as a Usenet post, and the code has Doxygen comments. That means that there is additional comment information in header, and that the user documentation, which is the normal way to get details of the API, is generated html.) > > Here, one problem is that there are 3 types that I don't know and would > have to look up. Incorrect. There are three types that are not standard C types, but if you are using this function, you don't have to look them up. You generally don't need to know what they are - indeed, knowing their details can easily lead to writing poorer and less adaptable or portable code. Only information about the callback function type is of interest, and even then it is only marginal - you look it up once when writing an appropriate callback function, taking negligible effort compared to writing the code itself. And because it is a named type, you know immediately that your function is suitable for other use-cases of that specific named type, such as for related dns lookup APIs. > The long version at least has all the info in one place: > > signed char > dns_gethostbyname( > const char *hostname, > struct ip_addr *addr, > void (*found)(const char *name, const struct ip_addr *ipaddr, > void *callback_arg), > void *callback_arg > ); > > That signed char return is unusual; why not 'int'? (How would you even > print an 'err_t' value anyway)? It seems that yet again, you need an explanation of fundamental points of software development. Today's lesson is on "abstraction". It does not matter what type "err_t" is, underneath. What matters is what you can /do/ with it. It is a type that is returned by this function (and many others), and which can be compared to ERR_OK, ERR_INPROGRESS, and ERR_ARG. That's all you need to know to use it here. Maybe on some targets (of this portable library), err_t is "signed char". Maybe on others it is "int32_t". Maybe in a newer version of the library, it will be an enum. It is also nice to know that it can be used in a switch, and cast to an int for printf. The documentation for the type can give more or less detail about it. But it is /not/ the same as a "signed char". That is an implementation detail which you should not rely on, and it is better - clearer, safer, more portable, more maintainable - if you do not know what it is. (I didn't know, until looking it up for these posts.) You use the correct type, as documented. Or look at the "ip_addr_t" type. It happens, at the moment, to be a struct. But it might have been a union. The size and contents of the struct depend on details of how the library is built - whether it has support for ipv4, ipv6, or both. Maybe a future version will also support ipv8, or ipv5 (I've heard some people are trying to make an IP protocol that covers more than IPv4, but without most of the complicating additional features of IPv6). It is an abstract type - you use it without knowing the details. > > That 'ip_addr_t' turns out to be a struct. For those I would use > typedefs anyway; I rarely use struct tags and you have to invent an > identifier in either case. > > Then we come to the function pointer, which is a quite a chunky one, but > let's work with it. Here, I would question whether you really need those > types in there, and especially those names. > > Presumably you have a regular function of your own with the same > signature? You anyway never directly 'call' this parameter with > arguments; you just pass it the address of your handler. Yes, that is how callbacks work. > > Or do you use that typedef as documentation? You can certainly do that if you want, in a declaration of the function - but it would be unusual to do so in the definition. The typedef is used primarily when passing the function pointer around, or storing it (in a local variable, in a struct, or whatever). > > Where does the info come from anyway; does the library export a suitable > typedef? In that case you might as well use it. But if not, info must > come from elsewhere. Of course it "exports" the typedef - it is in one of the library's headers. > > Anyway with some tweaks in place, using the struct typedef and using an > inline function pointer type, it would look like this: > > signed char > dns_gethostbyname( > const char *hostname, > IP_addr *addr, > void (*found)(char*, IP_addr*, void *), > void *arg > ); > > In this form, it is not wildly different from your short version. Not wildly different, just worse by counter-productively removing the abstractions and appropriate type names, and uselessly cluttering the declaration with unnecessary detail. > > So I would look at other ways of tidying up before resorting to > extraneous typedefs. > > But here, there may well be an extra reason to use a callback typedef; I > don't have the full details. > >
Re: Taming The Switch-Statement
Author: Dan Cross
Date: Wed, 21 Oct 2026 11:26
Date: Wed, 21 Oct 2026 11:26
26 lines
1830 bytes
1830 bytes
In article <11ba78m$3peq3$3@dont-email.me>, David Brown <david.brown@hesbynett.no> wrote: >On 21/10/2026 03:04, bart wrote: >> [snip] >> Anyway with some tweaks in place, using the struct typedef and using an >> inline function pointer type, it would look like this: >> >> signed char >> dns_gethostbyname( >> const char *hostname, >> IP_addr *addr, >> void (*found)(char*, IP_addr*, void *), >> void *arg >> ); >> >> In this form, it is not wildly different from your short version. > >Not wildly different, just worse by counter-productively removing the >abstractions and appropriate type names, and uselessly cluttering the >declaration with unnecessary detail. ...and also removing the `const` qualifiers on the first two pointer arguments to `found`. - Dan C.
Re: Taming The Switch-Statement
Author: bart
Date: Wed, 21 Oct 2026 11:29
Date: Wed, 21 Oct 2026 11:29
247 lines
10580 bytes
10580 bytes
On 21/10/2026 10:20, David Brown wrote: > On 20/10/2026 22:07, bart wrote: >> On 20/10/2026 16:02, David Brown wrote: >>> On 20/10/2026 16:11, bart wrote: >>>> * A further complication was to allow function pointers within that a >>>> declaration list >>> To me, the big disadvantage of C's declaration syntax is that it lets >>> you declare things of different (but related) types in the same >>> declaration. >> >> Yes, but that doesn't bite so much because it is uncommon. >> > > Unfortunately not - but it is uncommon to mix objects and function > declarations, or objects of wildly different real types. That's what I meant. >> const int const * const p; >> 1 2 3 >> >> const 1 applies to the basetype to its right. >> const 2 applies to the basetype to its left. > > These are redundant - they do the same thing. (I'd have preferred if > the ordering rules were strict - allowing only "const int" or "int > const" - but at least people are usually consistent in their style.) > >> >> (Both also can be in the middle with compound types like 'long long'!) >> >> const 3 is tricky: I think it applies to the * to its left, since it >> says that the pointer value itself is const. But 'p' has type 'pointer >> to', so it could apply to that directly. > > Yes - it is "p" that is const, not the "*". I would disagree. This type can also be written as: (const int const * const) There is no 'p' to apply to. The type describes a pointer to an integer. The first two consts say, redundantly, that the integer value is const. The third must then apply to the pointer. >> >> What about this however: >> >> int * const * p; >> >> 1 2 3 >> >> I think here, const 2 applies to * 1, which is to it's left, and can't >> apply to 'p' as that is the other side of the * 3. > > *p is of type "int * const" - thus you can use "*p" to access a pointer- > to-int, but you can't use *p to change that pointer-to-int. But what exactly does this 'const' apply to? I'm suggesting any 'const' applies either to the base type (the one on the left) or to a particular '*'. In that case the latter 'const's must apply right-to-left to the preceding '*'. >> Fair to say that is a complete mess, and it is error prone. > > No, it is not at all fair to say that. It is fair to say that a > different way of writing types might make it easier to understand - but > that's a /long/ way from saying it is "a complete mess". And you can't > call it "error prone" unless you know that people regularly use such > declarations, and often have bugs in their code as a result of doing so > incorrectly. I think that is an unrealistic claim. If there's any confusion about which const applies to which type element, then mistakes can be made. > You can write this in C++ : > > // This bit is only needed once > template <typename T> using ptr = T *; > > // p is a pointer to a const pointer to an int > ptr<const ptr<int>> p; > > > That's LTR syntax. Sure, it also has < > parentheses, but that's a > minor point since the ordering of the components is what apparently > matters so much. That it is LTR is now irrelevant because I find that incomprehensible anyway. You've turned a linear chain a nested structure ... oh never mind, I don't even want to go there with C++. > > Or you can write : > > typedef int * p_int; > const p_int * p; > > Thus p is a pointer to a "const p_int", where a "p_int" is a pointer to > an int. So, a common pattern with you is to use workarounds so that you effectively emulate LTR type patterns. Because they are easier to work with and understand. So you do appreciate how they facilitate things, even though they introduce an extra level of indirection and also disseminate the type information across the program. But you want to underplay how useful it would be to have natural LTR type declarations within a syntax. > These are different ways to write the same type, including one that is > LTR, and the main hinder to understanding remains the same - what is the > type for? If you create a type alias voluntarily (I don't mean structs where either a tag or a typedef needs to be created) then yes the name should impart something useful. But in my view this is often taken too far. Sometimes you have structs where every member has a different user-type. When you look further, you find they are all ints. That is just obfuscation. (I would accept enumeration types if the compiler can employ that info to improve type safety, but that seems to be limited.) >> I've showed even simple types or trying to use 'const' get becomes >> confusing. > > No, you haven't. OK. That is not surprising. >> It would make a HUGE difference: > > Your points below are all true, but IMHO all very minor, and do not add > up to anything much. It would eliminate half the issues with C's type syntax. Probably CDECL wouldn't need to exist. Lots of () disappear. It would make pointers-to-arrays more viable. But that's nothing in your view. OK again. > Your invented confusion. > That doesn't matter in practice. > I don't see that as significant. > > I do agree that the decay of expressions using array types into pointer > types is a source of error in C code - though I do not think it is as > bad as you do. I didn't say anything about, and that wouldn't be affected. > But I just don't see pointer-to-array expressions to be common enough > for the difference you describe to be important. If you're passing arrays to a function by-reference then the natural way is to a have a pointer to the array. C can do that, but nobody ever does so, probably because indexing is then so ugly. With my idea, (*A)[i] turns into A*[i], a bit less ugly. (In my language, it was A^[i]. However, some years ago I relaxed the rules to allow such in-between derefs to be dropped - the compiler will reinsert them as needed. So indexing looks like A[i], and there is the extra type safety of working with actual arrays, not pointers to things that may or may not be arrays. But then I also have pass-by-reference which achieves the same thing.) >> (4) For pointers to structs, these are the patterns: >> >> prefix * With -> With postfix * >> >> (*P).m P->m P*.m >> (**P).m (*P)->m P**.m >> (***P).m (**P)->m P***.m >> >> Which column looks the tidiest? > > Far and away the most common - by orders of magnitude - are pointers to > structs. "p->m" looks fine to me, and I prefer it to "p*.m". But where's the consistency? Sometimes "." is used for member selection, and sometimes "->". And with two pointer levels, you need both! (Again in my language, all those * (or ^) in the right column can be dropped. Some loss of transparency, but much, much cleaner code. But TBF, this could also be done in C without needing postfix *.) >> (5) With prefix *, a pointer type looks like 'T*'; notice the * is on >> the right, not left! With postfix *, it would all be consistent. You >> also wouldn't have 'T*A'; that would be an error (T* only happens >> when there is no name) > > The C declaration syntax is "declaration follows use". If "*" were a > postfix operator, then the declaration of a pointer-to-int would become: > > int p*; > > while the type of p would be "int *". So you would still have an > inconsistency there, unless you also changed the way C has its > declarations. The point is that currently you have 'int*' for the type, '*p' to declare p, and '*p' in expressions. The '*' switches sides for the bare type! >> (6) Your 'int * a, b' example would become: >> >> int a *, b; >> >> Much easier, even with that space, to see that '*' does not belong to >> the base type but is a modifier for that variable. > > It's still bad. I don't think finding a way to make it easier to write > bad code is a good idea. It wouldn't stay bad for long! Because if the intention was to declare two pointers, then it's easier to see that this is wrong. > So basically, the suggestion would change some very minor things - > mostly in subjective ways - and not actually do anything for aspects of > the language where there is more of a consensus that C is sub-optimal. > And for this, you would want a fundamental change to one of the most > used operators in all C code! Obviously you can't change prefix * now. A postfix /alternative/, in addition to prefix *, could have been introduced decades ago. So by the time /you/ encountered C, you might have been using the latter.
Re: Taming The Switch-Statement
Author: bart
Date: Wed, 21 Oct 2026 11:33
Date: Wed, 21 Oct 2026 11:33
15 lines
2296 bytes
2296 bytes
On 21/10/2026 12:21, David Brown wrote: > On 21/10/2026 03:04, bart wrote: >> Where does the info come from anyway; does the library export a >> suitable typedef? In that case you might as well use it. But if not, >> info must come from elsewhere. > > Of course it "exports" the typedef - it is in one of the library's headers. You could have said that in the first place. So it's not really a choice then is it? Then it makes sense to use what they have provided.
Re: Taming The Switch-Statement
Author: David Brown
Date: Wed, 21 Oct 2026 12:17
Date: Wed, 21 Oct 2026 12:17
615 lines
23499 bytes
23499 bytes
On 20/10/2026 21:24, Dan Cross wrote:
> In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com> wrote:
>> On 20/10/2026 09:01, David Brown wrote:
>>> On 19/10/2026 23:28, bart wrote:
>>
>>>> (Funny that when I suggest that nested loop breaks are uncommon,
>>>> everyone says I'm wrong! Some even write 200-line made-up examples to
>>>> prove their point.)
>>>
>>> I don't remember "everyone" saying you were wrong to say that nested
>>> loop breaks are uncommon - in fact, I don't remember /anyone/ saying
>>> that was wrong.
>>
>> (There was a LOT of antipathy towards my idea to fix the common case of
>> 'loop-break' clashing with 'switch-break', BECAUSE it did not fix the
>> problem of nested loop-break, which is uncommon, even though that wasn't
>> the aim.)
>
> Those are two different things. No one disagrees with you that
> "nested break from a switch inside of a loop" is relatively more
> common than other variants.
>
Quibble - that is not established to my satisfaction. I am not
convinced that wanting a nested break for "switch inside loop" is more
common than wanting it for "loop inside loop". So I neither agree nor
disagree with that claim. I don't, however, think it matters much -
both are situations that turn up sometimes in code, and definitive
answers are neither possible nor useful.
> Using that as an excuse not to provide a more general mechanism
> because you already have a proposal for the specific case is
> what I and others took you to task for. I find this ironic,
> since you rail against things in C that you do not like, citing
> the most ridiculous examples you can think of that do not show
> up in actual programs, yet for something where it is pointed out
> to you that your solution does not generalize, you claim that it
> does not need to because ... the general case rarely shows up in
> a real program.
>
>>>> There is no reason to abstract away that function pointer type.
>>>>
>>>> You probably do so in C /because/ the type involves * () and [] but
>>>> have somehow persuaded yourself that it just better that way.
>>>
>>> Do you hear that whooshing noise? It is the sound of the point flying
>>> far above your head.
>>>
>>> Here is an example of some sensible function typedefs, all from third-
>>> party code (so not my "peculiar" style)
>>>
>>> typedef void (*TimerCallbackFunction_t)( TimerHandle_t xTimer );
>>>
>>> TimerHandle_t xTimerCreate( const char * const pcTimerName,
>>> TickType_t xTimerPeriodInTicks,
>>> UBaseType_t uxAutoReload,
>>> void * pvTimerID,
>>> TimerCallbackFunction_t pxCallbackFunction );
>>>
>>> typedef void (*lwip_thread_fn)(void *arg);
>>> typedef void (*tcpip_init_done_fn)(void *arg);
>>> typedef void (*tcpip_callback_fn)(void *ctx);
>>> typedef void (* sys_timeout_handler)(void *arg);
>>> typedef void (*dns_found_callback)(const char *name,
>>> const ip_addr_t *ipaddr, void *callback_arg);
>>
>> This is the kind of C I find hard to read. There are lots of typedefs
>> but few uses of those typedefs that I can see, so I don't know how much
>> difference they make.
>
> You again missed the entire point. You may not see many uses
> of them, but as David says, the `typedef`s give you
> domain-specific *names* understandable to the programmer: a
> programmer can see the `sys_timeout_handler` type instantly know
> that this has a different function than the,
> `tcpip_callback_fn`, despite the having the same type.
Exactly.
>
> The other point is that the ridiculous examples you make up to
> illustrate your distaste for C declaration syntax basically do
> not appear in real programs.
>
>> [snip]
>> I've left in the regular parameter names, even though C doesn't need
>> them, but they are quite heavy - you don't really need those
>> Hungarian-style prefixes.)
>>
>> Well, I guess this buys you one thing: the parameter name for the last
>> parameter is to the right of its type, rather than be inside it. But a C
>> expert should not be fazed by that.
>>
>> Here is the same function as I might write it in an alternative syntax.
>>
>> I've kept the same names, but changed case-style and removed prefixes
>> and suffixes. I've capitalised user-type names:
>>
>> func TimerCreate( # (retain case if FFI import)
>> ichar timername,
>> Ticktype timerperiodinticks,
>> Ubasetype autoreload,
>> ref void timerid,
>> ref proc(Timerhandle) callbackfn)
>>
>> In this form, it's hard to see what benefit a typedef would give for
>> that last parameter; it is simple enough.
>
> What is your point? Do you have one? If you don't want to use
> C, don't use C.
>
> There are plenty of languages that can do this kind of thing
> that are not C and have syntax and semantics closer to what you
> seem to want. Here's an example in Rust:
>
> pub trait TimerHandle { ... }
>
> fn CreateTimer<T>(
> timer_name: &str,
> period: std::time::Duration,
> auto_reload: bool,
> timer_id: T,
> handler: fn(&dyn TimerHandle),
> ) -> Result<Timer<T>, TimerError>
>
> I didn't know what an `UBaseType_t` is, and while "autoreload"
> sounded pretty intuitive, I wasn't sure about the semantics, so
> I looked it up (the example comes from `FreeRTOS`). In this
> context, it is a boolean saying whether the timer should repeat
> with the given periodicity, or whether it is a one-shot.
FreeRTOS is written in C90 - a mistake, IMHO - and thus does not use
bool. Instead, it uses constants pdTRUE and pdFALSE of type
UBaseType_t. UBaseType_t is a type that is dependent on the target -
usually it is either 16-bit or 32-bit. But of course it doesn't matter
what the underlying types are - you use the typedef names, and the
documented constants.
>
> The timer_id is opaque to the timer, and it looks like it's used
> to facilitating the handler accessing timer-specific data. In
> C, passing it as a `void *` is used as a way to get a poor-man's
> overloading. But Rust has generics, I just made it generic over
> some type T.
FreeRTOS uses "void *" to mean "pointer to internal structure that you
shouldn't be messing with". It uses this far too often, and is, IMHO, a
poor design choice. (I also dislike the silly Hungarian naming.) I
would much preferred if there had been :
struct Internal_Timer_Struct;
typedef struct Internal_Timer_Struct * timer_id_t;
and then the parameter "timer_id_t timer_id". So in a re-write, it
would not be a generic. (You might choose to use a generic for the
handler function type, so that handler callbacks could have parameters
of other types, but not for the timer id.)
I am using these declarations from FreeRTOS (and LWIP) to demonstrate
the use of function typedefs in massively popular codebases, not to
claim FreeRTOS is a paradigm of C code design!
>
> If I were writing this from scratch in Rust, a language that has
> generics, closures, and so sum types, I'd do the whole thing
> differently; see the end for an example.
>
> But I digress. The point here is, Bart, that alternatives exist
> if you don't like C. You don't have to keep posting, over and
> over again, in comp.lang.c of all places, about how oh so
> terribly awful C is. If you don't want to program in C, simply
> don't program in C.
>
>>> Ask yourself why the typedefs are used. Look at the /names/. Those
>>> last four are all from the same network stack library, and are all
>>> typedefs for "void (*)(void*)".
>>
>> Until you mentioned it, I hadn't noticed. So typedef has done a good job
>> of hiding that useful fact! But looking more closely, it is the first
>> four of the last five.
>>
>> Let's take one:
>>
>> typedef void (*lwip_thread_fn)(void *arg);
>>
>> That 'arg' is not much use for a start (other than being a hint that
>> this particular (...) is where the parameters go).
>>
>> So, maybe this is used like this:
>>
>> void F(lwip_thread_fn lwip_thread_callback);
>
> I have no idea what you're trying to say here. The obvious (and
> honestly, excusable) syntax error aside, what is F? It's a
> function that, what, takes two function pointers?
>
> The type defined by `lwip_thread_fn` is a pointer to a function
> that takes a void pointer (`void *`) as its sole arugment, and
> returns `void` (that is, has no meaningful return value).
>
> Intuitively, the name implies that this is the function run as
> some thread, so we'd pass it to a thread creation function. The
> usual shape of those things is to give them a pointer to some
> function to run in the new thread, and a pointer to some
> arguments to be passed to that function.
Yes.
> For example:
>
> void
> whatever(void *argp)
> {
> struct Args *args = argp;
> while (keep_running()) {
> // Do the thing the thread is supposed to do.
> }
> thread_exit(SUCCESS);
> }
>
> thread_t *
> start_the_whatever_thread(void)
> {
> struct Args *args = malloc(sizeof(*args));
> if (args == NULL) abort();
> memset(args, 0, sizeof(*args));
> args->whatever = something();
> // etc...
> thread_t *thr = thread_create(whatever, args);
> if (thr == NULL) abort();
> return thr;
> }
>
> Something could start this as:
>
> thread_t *whatever_id = start_the_whatever_thread();
>
> At some point later, if you want to wait for the thread to
> exit, you'd run:
>
> (void)thread_join(whatever_id);
>
> Note this is decently complex behavior, but it's actually quite
> intuitive from the name and the type.
>
You have got a very clear picture here, much of it from the names of the
types. For a Rust programmer, you give a good impression of experience
with C :-)
The only mistake you made is that programmers working on systems using
FreeRTOS and the like, have a fear and loathing of "malloc", have never
heard of "abort()", and do not join our threads because they all run
until the power is switched off.
>> Here you have two identifiers imparting the sort kind of information; a
>> tautology.
>
> That's not what a tautology is.
>
>> If that function pointer pattern is common, or recurs in a suite of
>> functions, I might also have used a typedef, but with a common name.
>
> Then you loose the domain specificity; you can't tell from the
> name whether you need an LwIP thread, or a callback, or a
> something run in a different thread, or just a plain 'ol
> function you want to apply to run every now and again for a side
> effect.
Precisely.
>
>> Then only one would be needed, say:
>>
>> typedef void (*stack_callbackfn)(void);
>>
>> I might have done the same in that alternate syntax as it would start to
>> get cluttery: 'ref proc(ref void)', but also in order to define that
>> common pattern in one place.
>
> I dunno. Sounds like you have no idea what the code that David
> posted is meant to do. But that's a "you" problem.
>
>>>> Note that 'pcl' in my example /is/ a typedef; here it makes sense as
>>>> it is used in 100s of places. This function pointer occurs in only one
>>>> place.
>>>
>>> I'm sorry, I had mistaken you for a programmer who wanted to write good,
>>> clear programs. Naming things is not a shortcut to save keypresses.
>>
>> Isn't that one of the main uses of typedefs? So as to give a handy,
>> 'euphonious' one-token alias to an elaborate typedef.
>>
>> It also allows you to change the type in one place without having to
>> update hundreds of instances.
>>
>> It also allows the type to be opaque.
>
> The point is that the name you chose is meaningless to anyone
> other than you. What's a PCL? Phase Control Line? Printer
> Command Language? Photon Compressor Loop?
>
>> Saving keypresses is bonus benefit, but if it is shorter, then it can
>> also help readability as other critical elements are not overshadowed.
>>
>> So I'm not sure what objection you have to this particular use of it.
>
> Have you ever written a large program that was maintained by
> anyone other than yourself?
>
>> Here is the one place I do remember using typedef for a function pointer
>> (from an old project, not in C):
>>
>> type fnptr = ref proc
>>
>> repeat
>> (fnptr(pcptr^))^()
>> until stopped
>>
>> It's used as a cast, but reason I have it is because with simple cast
>> syntax, which is 'T(X)', the meaning without it would be ambiguous (a
>> grammar issue that I might fix one day).
>>
>> Rather than fallback to standard cast syntax (which is 'cast(X, T)'),
>> this was tidier.
>
> I can only guess at what this may mean. Hazarding a guess,
> `pcptr` is a "pointer to a program counter", which is a
> reference type to some type that represents some executable
> memory location in the program. You then have a loop that runs
> until "stopped" is true where you indirect the program counter
> pointer, cast it to a pointer to a function, and then invoke
> the function, right? One presumes you have the, "PC Pointer"
> because it changes over time, otherwise, you'd just give
> whatever it points to a name and call it.
>
> More generally, I fail to see what this is trying to
> demonstrate. If it's to show some sort of imagined superiority
> over C, I don't see it; that's sort of thing is easy enough to
> write:
>
> typedef void (*fnptr)(void);
>
> // Assume uintptr_t *pcptr is declared somewhere.
> do {
> ((fnptr)*pcptr)();
> } while (!stopped);
>
> E.g.,
>
> ```
> term% cat b.c
> #include <stdbool.h>
> #include <stddef.h>
> #include <stdint.h>
> #include <stdio.h>
>
> static void first(void);
>
> typedef void (*fnptr)(void);
> bool stopped = false;
> uintptr_t pc = (uintptr_t)first;
> uintptr_t *pcptr = &pc;
>
> void
> done(void)
> {
> printf("done\n");
> stopped = true;
> }
>
> void
> second(void)
> {
> printf("second\n");
> *pcptr = (uintptr_t)done;
> }
>
> void
> first(void)
> {
> printf("first\n");
> *pcptr = (uintptr_t)second;
> }
>
> void
> run(void)
> {
> do {
> ((fnptr)*pcptr)();
> } while (!stopped);
> }
>
> int
> main(void)
> {
> run();
> return 0;
> }
> term% gcc-16 -std=c11 -pedantic -o b b.c
> term% ./b
> first
> second
> done
> term%
> ```
Or just have :
fnptr pc = first;
fnptr *pcptr = &pc;
I don't see a need for "uintptr_t", except so that you have to have
casts like Bart had.
>
>>>> BTW what name would be given to such a function pointer type?
>>
>>> I have no idea what your code is supposed to do,
>>
>> It's a table of function pointers! All sharing the same signature.
>>
>> That's pretty generic. Is it really that hard to guess? You don't need
>> to know what they do, other than at some point they will be called as
>> handlertable[i](arg).
>
> That part is fine.
>
> What's utterly mystifying is what you are trying to show, if
> anything, by posting it. Is this supposed to prove some kind of
> point? Your code is not _a priori_ easier to understand than
> the equivalent C code; if anything, it is harder to understand
> because of your poorly chosen names.
>
> - Dan C.
>
> -->Rust implementation of Timers, mentioned above<--
>
> As mentioned above, if I were providing the FreeRTOS timers API
> in an alternative language, I'd write it differently from the
> start. In particular, I'd use an enumeration to describe the
> behavior with respect to repeating, and I'd use a closure to
> obviate the need for the opaque id. Something that isn't easy
> to express in the original API is a type of repeating timer that
> waits for the initial period, and then repeats with some
> different period.
>
> Something like this:
>
> ```rust
> pub mod timer {
> use std::sync::atomic::{AtomicBool, Ordering};
> use std::time::Duration;
>
> /// Errors that may occur when working with timers.
> #[derive(Clone, Copy, Debug)]
> pub enum Error {
> Running,
> CantStop,
> WontStop,
> }
>
> /// Describes the kind of a timer, as defined by its
> /// periodicity.
> ///
> /// A timer can either be a `OneShot` timer, which fires
> /// once, after its timeout expires, or it may be a Repeating
> /// timer, which will automatically reset after its handler
> /// is run and continue firing at the rate defined by the
> /// initial timeout, or it can be a periodic timer, that
> /// will fire the first time at the initial timeout, and
> /// then repeatedly a potentially different timeout. This
> /// use case can be simulated by a OneShot timer that
> /// creates a repeating Timer, but
> ///
> /// Once started, Repeating and Periodic timers continue
> /// firing until explicitly stopped.
> #[derive(Clone, Copy, Debug)]
> pub enum Kind {
> OneShot,
> Repeating,
> Periodic(Duration),
> }
>
> /// A named timer, that is handled by the given callback.
> pub struct Timer<'a, F> {
> pub name: &'a str,
> pub kind: Kind,
> pub timeout: Duration,
> callback: F,
> running: AtomicBool,
> // Whatever other innards...
> // ...
> }
>
> /// A read-only "view" into the timer.
> pub trait TimerView {
> fn name(&self) -> &str;
> fn kind(&self) -> Kind;
> fn timeout(&self) -> Duration;
> }
>
> impl<'a, F: Fn(&dyn TimerView)> Timer<'a, F> {
> /// Creates a new named timer of the given kind with an
> /// initial timeout. When the timeout expires, it will
> /// automatically invoke the given handler.
> pub fn new(
> name: &'a str,
> timeout: Duration,
> kind: Kind,
> callback: F,
> ) -> Timer<'a, F> {
> let running = AtomicBool::new(false);
> Self {
> name,
> kind,
> callback,
> timeout,
> running,
> }
> }
>
> /// Starts the timer.
> pub fn start(&self) -> Result<(), Error> {
> if self.running.swap(true, Ordering::AcqRel) {
> return Err(Error::Running);
> }
> self.arm(self.timeout)?;
> Ok(())
> }
>
> /// Stops the timer.
> ///
> /// Note that this inherently races with the timer firing,
> /// and a timer event that occurs while we are disabling
> /// the timer may still invoke `fired` after this returns.
> ///
> /// Callers are advised to determine definitively that
> /// there are no events pending for this timer before
> /// destroying the `Timer` object.
> pub fn stop(&self) -> Result<(), Error> {
> let was_running = self.running.swap(false, Ordering::AcqRel);
> if !was_running {
> return Err(Error::WontStop);
> }
> self.disarm();
> Ok(())
> }
>
> // Automatically called when the timeout fires.
> //
> // # Safety
> //
> // Nothing may be mutably borrowing a reference to the
> // Timer object when this is called.
> pub(super) unsafe fn fired(&self) -> Result<(), Error> {
> if !self.running.load(Ordering::Acquire) {
> return Ok(());
> }
> (self.callback)(self);
> match self.kind {
> Kind::OneShot => Ok(()),
> Kind::Repeating => self.arm(self.timeout),
> Kind::Periodic(period) => self.arm(period),
> }
> }
>
> // Arranges for `self.fired(self)` to be called when
> // the given timeout expires.
> fn arm(&self, timeout: Duration) -> Result<(), Error> {
> // Does whatever one does here to actually arm the
> // timer (e.g., calls a HAL to actually program a
> // physical timer to interrupt after the amount of
> // time specified by `Duration`, for example).
> // ...
> Ok(())
> }
>
> // Disables an armed timer, so that it does not fire
> // after this returns.
> fn disarm(&self) -> Result<(), Error> {
> // whatever one does here to disarm an active timer
> // ...
> Ok(())
> }
> }
>
> impl<F> TimerView for Timer<'_, F> {
> fn name(&self) -> &str { self.name }
> fn kind(&self) -> Kind { self.kind }
> fn timeout(&self) -> Duration { self.timeout }
> }
> }
> ```
>
> One might use this with something like,
>
> ```
> let value = 42;
> let cb = move |timer: &dyn timer::TimerView| {
> println!(
> "Timer '{}' fired; value is {} and duration was {} ms",
> timer.name(),
> value,
> timer.timeout().as_millis()
> );
> };
> let timeout = std::time::Duration::from_millis(100);
> let timer = timer::Timer::new("timer", timeout, timer::Kind::OneShot, &cb);
> timer.start().expect("Timer started");
> //... at some point the timer fires and prints,
> // 'Timer 'timer1' fired; value is 42 and duration was 100 ms'
> }
> ```
Re: Taming The Switch-Statement
Author: David Brown
Date: Wed, 21 Oct 2026 12:21
Date: Wed, 21 Oct 2026 12:21
27 lines
2761 bytes
2761 bytes
On 21/10/2026 13:33, bart wrote: > On 21/10/2026 12:21, David Brown wrote: >> On 21/10/2026 03:04, bart wrote: > >>> Where does the info come from anyway; does the library export a >>> suitable typedef? In that case you might as well use it. But if not, >>> info must come from elsewhere. >> >> Of course it "exports" the typedef - it is in one of the library's >> headers. > > You could have said that in the first place. So it's not really a choice > then is it? What do you mean? There is an API in "dns.h" that uses typedefs such as "ip_addr_t" and "dns_found_callback". /Obviously/ those typedefs are also included in the header (or other headers included by "dns.h"). This is not something that I should have had to point out. > > Then it makes sense to use what they have provided. > It always makes sense to use the types provided.
Re: Taming The Switch-Statement
Author: David Brown
Date: Wed, 21 Oct 2026 13:10
Date: Wed, 21 Oct 2026 13:10
184 lines
7943 bytes
7943 bytes
On 21/10/2026 00:43, bart wrote:
> On 20/10/2026 22:44, Dan Cross wrote:
>> In article <11b8j17$3btus$1@dont-email.me>, bart <bc@freeuk.com> wrote:
>>> On 20/10/2026 20:24, Dan Cross wrote:
>>>> In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com>
>>>> wrote:
>>>
>>>> The point is that the name you chose is meaningless to anyone
>>>> other than you. What's a PCL? Phase Control Line? Printer
>>>> Command Language? Photon Compressor Loop?
>>>
>>> Within the context of that application then it would be clear. You're
>>> just being overly hostile.
>>
>> Not really. You are, I presume, posting that code to try and
>> make some kind of point about how "readable" it is. But it's
>> not readable unless you already know what it does.
>
> What it does not relevant. This is simply defining an array of T. But
> because T happens to be a function pointer, DB insists that an alias
> must be created, and a new name invented.
I did not "insist" or say that an alias "must" be created. I said
that's normally what you should do in real code, to make it clear,
readable and maintainable.
Note that I wrote (in regard to the "pcl" stuff) :
"""
I have no idea what your code is supposed to do, so I have no idea what
names would be good. Presumably you /do/ know what it is for - such as
what "pcl" means - so /you/ pick good names. Maybe "host_handler_fn" ?
"""
If "pcl" makes sense in the context of your code, that's fine - use it
in your names.
But don't use generic names where specific names impart useful
information. Don't re-use generic names because of a coincidence in the
underlying implementation - use names that make sense where they are used.
>
> Why? Probably because in C, the syntax for function pointers gets hairy.
No, this is all because I (and Dan) know how to write good code in a
clear (to appropriate readers) and maintainable manner. The syntax is
irrelevant. We appreciate that you find C's declaration syntax
confusing and difficult - I think that after the first two or three
hundred repetitions, it finally sank in. But please stop projecting
your weaknesses and prejudices onto other people. I do not name
function pointer types because of C's syntax - I name them because the
code is better in many ways when the types are named. I would do the
same in Pascal, Rust, Ada, or any other language, regardless of the syntax.
>
>> On the other hand, the code David posted _is_ readable, because
>> it uses the language to encode domain-specific information into
>> type names.
>
> Maybe we should create aliases for function signatures more often then,
> then we can encode that extra info.
>
> So that instead of, for example:
>
> void SomeFunc(int x, int y) {printf("%d %d\n", x, y);}
>
> you do:
>
> typedef void Take2Ints(int x, int y);
>
> Take2Ints SomeFunc {printf("%d %d\n", x, y);}
>
Maybe we should not. That is not helpful to code clarity. It is a
pointless generic name (showing that you /still/ do not understand the
fundamental matter of giving useful and informative names), and instead
of /giving/ useful additional information, it /hides/ details at the
point in the code where they are vital.
Now, if you had a concept of "Coordinate handler" that was expected to
receive an x, y pair and do something with them, then it is possible
that you would have a header file "coordinate_handlers.h" with :
typedef void Coordinate_Handler_Func(int x, int y);
and some related function declarations :
Coordinate_Handler_Func dummy_handler;
Coordinate_Handler_Func simple_printer;
Coordinate_Handler_Func fly_to_new_coordinates;
You are putting the emphasis here on what sort of usage you expect for
these functions, with the assumption that code using them knows how to
call them. This could be handy if you have another module that needs to
build an array or other data structure with these functions - it does
not care about the implementation details, and uses the function type
(or a pointer to the function type) without looking at its contents:
#include "coordinate_handlers.h"
size_t build_coordinate_handler_array(
Coordinate_Handler_Func * hs, size_t max_handlers)
{
assert(max_handlers >= 3);
hs[0] = &dummy_handler;
hs[1] = &simple_printer;
hs[2] = &fly_to_new_coordinates;
return 3;
}
A caller function might have :
#include "coordinate_handlers.h"
void call_handler(size_t handler_no, int x, int y) {
assert(handler_no < no_of_handlers);
Coordinate_Handler_Func h * handlers[handler_no];
h(x, y);
}
Handler implementations would be written normally :
#include "coordinate_handlers.h"
void simple_printer(int x, int y) {
printf("%d %d\n, x, y);
}
Then later when you decide to go to 3 dimensions, you need to change
code that calls these handlers, and you need to change the handler
implementations (and you'll get compile-time errors until you do), but
generic "in the middle" code like "build_coordinate_handler_array" is
unchanged.
But if the code also happened to need lots of functions for drawing
titles at x, y coordinates, it would have :
typedef void Title_Drawer_Func(int x, int y);
You would /not/ re-use the same typedef, just because the implementation
is the same, when the /purpose/ is different.
> If you have a suite of functions sharing the signature, then it might be
> a good idea. But funnily enough, you never see this being done.
>
Given that it is not remotely close to valid C, I don't think it is
particularly surprising.
> (I don't know if this is legal C; but it works fine with my compiler:
Your compiler is not a C compiler - it's a compiler for an undefined and
undocumented superset of an undefined and undocumented subset of an
undocumented version of C. If that's all you need, there's nothing
wrong with that - but what works or does not work with your compiler is
no indication of what is or is not "legal" C.
>
> c:\m>type fred.c
> #include <stdio.h>
>
> typedef void Take2Ints(int x, int y);
>
> Take2Ints SomeFunc{printf("%d %d\n", x, y);}
>
> int main(void) { SomeFunc(10, 20); }
>
> c:\m>bcc -r -q fred
> 10 20
>
> )
>
>> Yeah, you really just don't get it.
> One of us doesn't get it.
Exactly. I'm fairly sure you are alone here.
Re: Taming The Switch-Statement
Author: Dan Cross
Date: Wed, 21 Oct 2026 13:22
Date: Wed, 21 Oct 2026 13:22
126 lines
6076 bytes
6076 bytes
In article <11baah2$3te3v$1@dont-email.me>,
David Brown <david.brown@hesbynett.no> wrote:
>On 20/10/2026 21:24, Dan Cross wrote:
>> In article <11b7k22$2v8e5$1@dont-email.me>, bart <bc@freeuk.com> wrote:
>>> [snip]
>>> (There was a LOT of antipathy towards my idea to fix the common case of
>>> 'loop-break' clashing with 'switch-break', BECAUSE it did not fix the
>>> problem of nested loop-break, which is uncommon, even though that wasn't
>>> the aim.)
>>
>> Those are two different things. No one disagrees with you that
>> "nested break from a switch inside of a loop" is relatively more
>> common than other variants.
>
>Quibble - that is not established to my satisfaction. I am not
>convinced that wanting a nested break for "switch inside loop" is more
>common than wanting it for "loop inside loop". So I neither agree nor
>disagree with that claim. I don't, however, think it matters much -
>both are situations that turn up sometimes in code, and definitive
>answers are neither possible nor useful.
Ok, that's fair; I shouldn't say "no one disagrees".
>> [snip]
>> There are plenty of languages that can do this kind of thing
>> that are not C and have syntax and semantics closer to what you
>> seem to want. Here's an example in Rust:
>>
>> pub trait TimerHandle { ... }
>>
>> fn CreateTimer<T>(
>> timer_name: &str,
>> period: std::time::Duration,
>> auto_reload: bool,
>> timer_id: T,
>> handler: fn(&dyn TimerHandle),
>> ) -> Result<Timer<T>, TimerError>
>>
>> I didn't know what an `UBaseType_t` is, and while "autoreload"
>> sounded pretty intuitive, I wasn't sure about the semantics, so
>> I looked it up (the example comes from `FreeRTOS`). In this
>> context, it is a boolean saying whether the timer should repeat
>> with the given periodicity, or whether it is a one-shot.
>
>FreeRTOS is written in C90 - a mistake, IMHO - and thus does not use
>bool. Instead, it uses constants pdTRUE and pdFALSE of type
>UBaseType_t. UBaseType_t is a type that is dependent on the target -
>usually it is either 16-bit or 32-bit. But of course it doesn't matter
>what the underlying types are - you use the typedef names, and the
>documented constants.
Thanks for the context. Your point that the underlying type
doesn't matter is salient: it's opaque to the programmer, but
99% of the time the programmer doesn't need to worry about the
details.
>> The timer_id is opaque to the timer, and it looks like it's used
>> to facilitating the handler accessing timer-specific data. In
>> C, passing it as a `void *` is used as a way to get a poor-man's
>> overloading. But Rust has generics, I just made it generic over
>> some type T.
>
>FreeRTOS uses "void *" to mean "pointer to internal structure that you
>shouldn't be messing with". It uses this far too often, and is, IMHO, a
>poor design choice. (I also dislike the silly Hungarian naming.) I
>would much preferred if there had been :
>
> struct Internal_Timer_Struct;
> typedef struct Internal_Timer_Struct * timer_id_t;
>
>and then the parameter "timer_id_t timer_id". So in a re-write, it
>would not be a generic. (You might choose to use a generic for the
>handler function type, so that handler callbacks could have parameters
>of other types, but not for the timer id.)
>
>I am using these declarations from FreeRTOS (and LWIP) to demonstrate
>the use of function typedefs in massively popular codebases, not to
>claim FreeRTOS is a paradigm of C code design!
Oh interesting; in this case, I had assumed it was treated as
a callback-specific type so one could plumb extra context into
the handler; the documentation I saw suggested it could be used
by the handler to disambiguate several timers reusing the same
handler function.
>> For example:
>>
>> [snip]
>>
>> Note this is decently complex behavior, but it's actually quite
>> intuitive from the name and the type.
>
>You have got a very clear picture here, much of it from the names of the
>types. For a Rust programmer, you give a good impression of experience
>with C :-)
I've been known to dabble.
>The only mistake you made is that programmers working on systems using
>FreeRTOS and the like, have a fear and loathing of "malloc", have never
>heard of "abort()", and do not join our threads because they all run
>until the power is switched off.
Ha, fair; that was just a made-up example, based on other thread
libraries I have used (in C). I didn't mean for it to be
interpreted strictly in the context of FreeRTOS! :-D
> [snip]
>
>Or just have :
>
> fnptr pc = first;
> fnptr *pcptr = &pc;
>
>I don't see a need for "uintptr_t", except so that you have to have
>casts like Bart had.
Yes. But I wanted to remain faithful to his original, to show
that one could write a more-or-less exact transliteration in C
that was extremely similar to his chosen syntax.
>> [Snip a bunch of Rust code; the point of which being that
>> bart need not complain about lack of an alternative to C]
- Dan C.
Re: Taming The Switch-Statement
Author: David Brown
Date: Wed, 21 Oct 2026 13:28
Date: Wed, 21 Oct 2026 13:28
54 lines
4139 bytes
4139 bytes
On 21/10/2026 03:23, Keith Thompson wrote: > David Brown <david.brown@hesbynett.no> writes: >> On 19/10/2026 23:27, Janis Papanagnou wrote: > [...] >>> * a b PN (Polish Notation) >> >> There is no term "Polish Notation" - except as occasionally used to >> mean /postfix/ as a short form of "Reverse Polish Notation". RPN was >> invented, or at least popularised, by the Polish logician Jan >> Łukasiewicz (I admit to looking that up on Wikipedia!). There is no >> "PN" opposite. > > Yes, there most certainly is, and "* a b" is a good example of it. > > https://en.wikipedia.org/wiki/Polish_notation > > Jan Łukasiewicz invented what we now call Polish notation in 1924. > `+ 3 4` is an example (which yields 7). Lisp syntax is more or > less Polish notation with added parentheses. (I'm sure the phrase > "more or less" is doing a lot of work.) > > Reverse Polish Notation, RPN, is very well known because it's > used by some calculators, particularly those made by HP. It's a > postfix notation. An example of RPN is `3 4 +` (which also yields 7). > > I've never seen the term "Polish Notation", without "Reverse", used > to refer to postfix notation. PN is prefix; RPN is postfix. I have - it was used as a "short" version of "Reverse Polish Notation". I have not, that I recall, seen the term "Polish Notation" used to refer to prefix notation until Janis' post. But I accept that this is purely based on my experience of when /I/ have heard (or not heard) the term. I stand by my assertion that "prefix" would have been better in the context, but I was wrong about "Polish Notation" not being an established term in its own right. > > I see that Janis already pointed out your error. I'm disappointed > that your followup did not acknowledge it. (I'm not commenting on the > rest of what Janis wrote.) > I had not wanted to dwell on it. (I had started a longer reply to Janis, but scrapped it.) I had simply intended to recommend terms that had no chance of being misinterpreted, given that some of Janis' terms had been. But yes, I should have acknowledged that mistake on my part. Thus I have learned a new term from Janis, and perhaps he has learned a little of the another meaning of "monadic" from my post.
Page 7 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