Hi, welcome to the forum. I come from a C/C++ background, and I have to disagree with you Zig’s for
loop syntax, in my opinion, is better than the one in C/C++. Why? If we look at the typical use pattern of for
loops in those languages, you’re usually iterating over a range of something: from the first character of a string until the '\0'
, from base_ptr
to end_ptr
, or over a range like for (size_t i = 0; i < 10; i++)
. The point is, my use of loops in C/C++ is pretty consistent.
For
loops: for iterating over a given range of something.
While
loops: for everything else.
Now, if you look at the syntax of a for
loop in C/C++, you need to provide three statements, all optional: an initializer, a condition, and the final statement executed at the end. That’s three potential points of failure, three opportunities to make a mistake.
How many times have you encountered a bug because you didn’t use the right types say, an initializer of type int
and a condition of type unsigned
? I know I have (though with more experience, it happens less). And how many times have you mistakenly written for (size_t i = 0; i <= 10; i++)
instead of for (size_t i = 0; i < 10; i++)
? That still happens to me if I’m not careful. I can’t even count how many times my C++ program has crashed because, in an iterator loop, I used ++it
instead of it++
I just prefer the prefix increment aesthetic in C.
My point is, the for
loop in Zig, combined with the Zig compiler and bounds checking, creates an environment where there’s less room for error. You don’t have to create and initialize the iterator properly; it’s deduced from the range you’re iterating over. There’s no room to mess up the condition because the only condition is the range itself, and the compiler will throw an error if it’s invalid. I understand the argument about not being able to easily iterate backward in Zig, but that fits with the philosophy of making the correct thing easier—loops that decrement have caused me countless issues.
In any case, I get your opinion, and I wouldn’t mind if they changed or improved the for
loop. But as it stands, the current one works well for me, and when it doesn’t, the while
loop fills the gap which seems very much in line with how these loops are used in C/C++.