Sujet : Re: Loops (was Re: do { quit; } else { })
De : 643-408-1753 (at) *nospam* kylheku.com (Kaz Kylheku)
Groupes : comp.lang.cDate : 16. Apr 2025, 04:30:25
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <20250415201754.605@kylheku.com>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
User-Agent : slrn/pre1.0.4-9 (Linux)
On 2025-04-16, James Kuyper <
jameskuyper@alumni.caltech.edu> wrote:
On 2025-04-15, bart <bc@freeuk.com> wrote:
Note that C's for-loop is dumb; it merely take three expressions A B C
that can be completely unrelated, and arranges them into a loop:
>
A; while (B) {...; C}
Note that this problem is not unique to the for() statement. An
assignment statement allows you to arrange three unrelated expressions
together like
>
A = B + C;
>
"Doctor, it hurts when I hit my head with a hammer!"
"Then stop doing that."
>
The key to using the for() statement is to make sure the three
expressions are related appropriately.
The observation is valid that the three expressions often fall into a
pattern by which they can be condensed.
for (var = from; var < to; var++)
can be expressed by a construct which mentions var ony once,
and omits the operators.
You can obtain this with the preprocessor and be reasonably happy.
Similarly, sometimes assignment statements fit patterns which
lead us to want to condense them.
One pattern is
A = A + C
for which we have
A += C
in order to avoid mentioning A twice, and of course for
A = A + 1
we have
++A (as well as A++ which lets us capture the prior value)
C pointer arithmetic affords us a way to condense this pattern also:
A[i] = B[i] + C[i]
in a loop body where these expressions are repeated multiple times,
and are both read and written, we can achieve economy of expression with
double a = &A[i];
double b = &B[i];
double c = &C[i];
*a = *b + *c;
Sometimes code like this shamelessly uses preprocessing, hopefully
confined to a single translation unit.
#define a A[i]
#define b B[i]
#define c C[i]
a = b + c
C provides some decent syntactic sugars to shorten code.
It seems shortsighted to criticize C for having a verbose for loop
construct, given that it can be macroed over, and that other devices
more than make up for it.
-- TXR Programming Language: http://nongnu.org/txrCygnal: Cygwin Native Application Library: http://kylheku.com/cygnalMastodon: @Kazinator@mstdn.ca