Sujet : Re: Loops (was Re: do { quit; } else { })
De : Keith.S.Thompson+u (at) *nospam* gmail.com (Keith Thompson)
Groupes : comp.lang.cDate : 17. Apr 2025, 03:18:59
Autres entêtes
Organisation : None to speak of
Message-ID : <87ikn3zg18.fsf@nosuchdomain.example.com>
References : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
User-Agent : Gnus/5.13 (Gnus v5.13)
bart <
bc@freeuk.com> writes:
[...]
The increment is part of its behaviour. At the language level, I could
explain how FOR is implemented, but I'd rather not do that.
Whereas for a language like C which is defined by a written standard,
the standard *must* specify the behavior at the language level
(not in terms of generated intermediate or machine code).
The fact that
for (int i = INT_MAX-1; i <= INT_MAX; i++);
has undefined behavior can be rigorously inferred from the language
definition.
A note that upper and lower limits must be in the range i64.min + s
.. i64.max - s (where s is the step size) can suffice.
>
What's far more useful is that it naturally works with i64 so has
limits 4 billion times bigger than you get with C's default 'int'
type.
You know, of course, that C's int type is not necessarily 32 bits.
There is no "default" for the width of int. If you had written "with
32-bit int", that would have been clear and correct.
[...]
Maybe the language can detect overflow, but it won't help, as you want
to loop to stop not abort the program. So it is not a solution.
If you want to implement, say, an Ada-style for loop, detecting
overflow is not an issue at the language level. The issue is that
for the following (I think the Ada syntax is clear enough):
for I in Integer'Last-1 .. Integer'Last loop
// whatever
end loop;
the language semantics specify that the body of the loop must be
executed with I equal to Integer'Last-1, and then with I equal to
Integer'Last. It's the compiler's job to figure out how to do that,
either without triggering an overflow or by handling it cleanly enough
that it doesn't change the behavior.
C's for loop, which is both lower level and more flexible, does not
impose that particular burden on the compiler. It's up to the
programmer to ensure that a given for loop behaves as desired.
-- Keith Thompson (The_Other_Keith) Keith.S.Thompson+u@gmail.comvoid Void(void) { Void(); } /* The recursive call of the void */