For loops are translatable from:
for(initialize; condition; increment) { ... }
to: initialize;
while(condition) {
...
increment
}
(more or less, some scoping things not encompassed by the above; this is also how pretty much every for loop in a C-syntax language works) The condition of a for loop is equivalent to a while loop's condition. So yes, length - 1 < length will be true on the first iteration, which is fine because the loop continues as long as that condition is true.What the above approach takes advantage of is that when underflow eventually happens you'll have this condition:
MAXINT < length
Which will terminate it for all possible values of length.
Re:Why do arrays start at 0?
by bobthepanda on Wednesday August 24, 2022 @04:01PM
(#32584984)
It‘s an unsigned int, so past 0 it overflows back to the maximum
Re:Why do arrays start at 0?
by 411111111111111 on Wednesday August 24, 2022 @04:03PM
(#32585022)
Ooh, i see. I wasn't aware that they under/overflow at 0 when they're unsigned. Thanks for broadening my horizon!
It loops while the condition is true. When an underflow happens, it stops being true.
Re:Why do arrays start at 0?
by msk-lywenn on Wednesday August 24, 2022 @04:00PM
(#32584970)
It’s a condition to run, not a condition to stop
That was my reaction - why should anyone think it might be the latter? Are there languages that do have such a syntax without explicit keywords ("do...until")?
Re:Why do arrays start at 0?
by msk-lywenn on Saturday September 03, 2022 @02:19PM
(#32704576)
I think lisp or scheme does. I was often confused by that when I was playing with it
Re:Why do arrays start at 0?
by billforsternz on Wednesday August 24, 2022 @04:46PM
(#32585517)
The loop continues until i transitions from 0 to 0 minus 1. 0-1 in this case actually doesn't equal -1 since size_t is an unsigned type, instead it wraps around to be the largest possible positive integer instead. TLDR; yes as you speculate it terminates when the number underflows.
why doesn't that loop end instantly?
I mean length - 1 < length should always be true, right?
Or does it only terminate when the number underflows? Terribly confused here