What is (<some command/variable> i = 0; i < z; i++)?

I’ve seen 3 different programming languages with that exact same coding structure, what does it mean? What is i, and what is i++?

It’s a C-style for loop, typical full syntax is

for (initialization; condition; post) { /* loop body */ }

Your example would be something like

for (int i = 0; i < z; i++) { /* ... */ }

i in this case would be an integer.
i++ means “increment i by 1”.

Semantically it’s like this:

  1. Assign 0 to i.
  2. Check if i is less tnan z.
  3. If it isn’t, go to (7).
  4. Execute loop body (in which current value of i is available).
  5. Increment i by 1.
  6. Go to (2).
  7. End.

More information e.g. here.

Okay, I could see that, so int means initial value or integer?


int is a type declaration. It declares that the variable i contains an integer.

Furthermore, it declares that the variable referred-to as i within the body of this loop exists only within the body of this loop! (This helps to prevent unwanted interference between loops, so-called “coupling” caused by using the same variable in more than one place.)

  1. First, i is initialized to zero. Then, the loop begins.
  2. The loop executes zero or more times, while (i < z). (If the condition is initially false, the loop does not execute at all.)
  3. At the end of each execution of the loop, i is incremented (i++).

This construct first appeared in the now-venerable C programming language, circa 1971, and has been shamelessly copied ever since. (I don’t know if they cabbaged it from something even older …)

footnote, even though you usually see

type declaration = value;
if (value < maximum)

that’s the same as

type declaration = value; if (value < maximum) { value++; }

you’re only filling in data for a structure of sorts, the kind of that a compiler would know about. <command> arg arg arg — or — <command>(arg; arg; arg), the first one is more of a console thing and then programs do language the other way, most of the time at least. Brainfuck is a thing you guys. Think about that.

Something about that doesn’t make sense. I’ve definitely 100% used the variable “i” after defining it as a loop in other places outside the brackets, and it worked exactly as expected as a parameter I could arbitrarily float.

“Winging it” is a really, really bad idea. Just saying.

1 Like

That’s… not how scope works


I stand by what I said:


However, you should not declare the variable ambiguously, such that there might be simultaneously more than one interpretation of i. I believe that the compiler should actually call-you-out on that. Do not declare i at the function or global level if you at the same time use the same identifier within a loop or block context.