Sujet : Re: Loops (was Re: do { quit; } else { })
De : bc (at) *nospam* freeuk.com (bart)
Groupes : comp.lang.cDate : 16. Apr 2025, 15:45:56
Autres entêtes
Organisation : A noiseless patient Spider
Message-ID : <vtofr2$2db8v$2@dont-email.me>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
User-Agent : Mozilla Thunderbird
On 16/04/2025 15:09, Scott Lurndal wrote:
bart <bc@freeuk.com> writes:
On 15/04/2025 20:07, Scott Lurndal wrote:
bart <bc@freeuk.com> writes:
On 15/04/2025 14:19, Kaz Kylheku wrote:
>
Thats's fine. But it means a real 'for' loop doesn't exist in C; you
have to emulate it using that 3-way construct, which is naff, and also
error prone.
>
Real for loops _are_ a three-way construct.
>
135 FOR I=1 TO 10 STEP 2 [BASIC]
>
for(i = 1; i < 11; i += 2) [C/C++]
>
do 1 = 1, 10, 2 [FORTRAN]
>
Any step other than 1 is unusual. So Basic and Fortran would typically be:
>
for i = 1 to 10 # 6 tokens; Basic
do i = 1, 10 # 6 tokens; Fortran
for i = 1, 10 # 6 tokens; Lua
for i to 10 do # 5 tokens; Mine (using default start)
to 10 do # 3 tokens; Mine (when index is not needed)
>
Let's look at that C again:
>
for (int i = 1; i < 11; i += 1) # 15 tokens; C
>
for(i = 1; i++ <= 10;)
So real for loops are a /two-way/ construct?
In any case, that doesn't do the same as the others, as it iterates over 2 to 11 inclusive, not 1 to 10.
You might try 'for (i=0; i++ < 10);)', but there's still a problem: you have to offset the start value by -1. This mean that to iterate over the 0..9 bounds of 10-element array, you'd have to write:
for (i = -1; i++ < 9;)
It becomes exclusive at the lower end, and top becomes inclusive despite using '<' instead of '<='.
The real problem is that the index is incremented in the wrong place. Now look again at that Fortran:
do i = 1, 10 # iterate over 1..10 inclusive
do i = 0, 9 # iterate over 0..9 inclusive
It now looks even better: gorgeously simple, clean, intuitive - and still shorter.