A for loop could be called syntactic sugar. for (init; test; increment) {body} It translates to: init; while (test) {body; increment} Init. If test do body and do increment. Repeat until test fails. Yes, you could intermingle body and increment. I've done it, and it works. Don't though - the point of the for() loop is readability. In addition to readability it controls the scope of the token you're defining during init. That variable is (or should be) scoped to the loop only, and be inaccessible outside of it. Helps reduce "wth just happened" debugging moments when an init goes wrong. Answer from kagato87 on reddit.com
🌐
W3Schools
w3schools.com › js › js_loop_for.asp
JavaScript for Loop
For Loops can execute a block of code a number of times.
Discussions

What is the full "for" loop syntax in C? - Stack Overflow
I have seen some very weird for loops when reading other people's code. I have been trying to search for a full syntax explanation for the for loop in C but it is very hard because the word "for" a... More on stackoverflow.com
🌐 stackoverflow.com
c - Can someone explain what a "for" loop is in the simplest terms possible? - Stack Overflow
The iterate collection or for each loop is used to do something with each element in a collection of elements, like a list, array or map / associative array. The syntax for this style of loop is less consistent across languages, but generally takes a form like for (element in collection) statement; More on stackoverflow.com
🌐 stackoverflow.com
Syntactic sugar in C - (ab)using "for" loops

There is a caveat though. As the author said in the summary section, while the prologue/epilogue example should work in normal conditions, it would break (pun not intended) when you break or goto inside the loop. And break inside the loop happens a lot. Be careful when using this to manage resources. In C++, using a stack allocated object with a destructor in the initialization part can handle exceptional control flows.

More on reddit.com
🌐 r/programming
30
211
May 11, 2014
What makes for-loops difficult for beginners?
The syntax of for loops in C-like languages is not exactly intuitive. Even the name "for" seems like a rather non-descriptive, meaningless word. I don't know how for loops are commonly taught, but perhaps it is common to see them introduced with examples like this: for (int i = 0; i < 10; ++i) print i; Now, it is true that the most common use of for loops is to repeat something a certain number of times like this, but if this is how for loops are introduced, then I can understand how they seem mysterious. What in the world is all that garbage syntax doing there for a simple counting loop? Why are there all of those semicolons, and why do you have to say ++i? Etc. It would be better, I think, to teach that the loop for (initialization; condition; update) statement; is (almost) equivalent to initialization; while (condition) { statement; update; } and then show several examples of the same code written in both of these ways to demonstrate and reinforce this equivalence. These examples should include not only the common case of repeating a statement a certain number of times, but also other uses of the for loop, such as finding the length of a C string (where the condition is like *p != '\0'). More on reddit.com
🌐 r/learnprogramming
7
2
March 30, 2013
🌐
GeeksforGeeks
geeksforgeeks.org › dsa › for-loop-in-programming
For loop in Programming - GeeksforGeeks
3 days ago - A for loop has three main parts: initialization, condition, and update.
🌐
W3Schools
w3schools.com › c › c_for_loop.php
C For Loop
Statement 3 increases a value each time the code block in the loop has been executed: i++ ... int sum = 0; int i; for (i = 1; i <= 5; i++) { sum = sum + i; } printf("Sum is %d", sum); Try it Yourself »
A for loop could be called syntactic sugar. for (init; test; increment) {body} It translates to: init; while (test) {body; increment} Init. If test do body and do increment. Repeat until test fails. Yes, you could intermingle body and increment. I've done it, and it works. Don't though - the point of the for() loop is readability. In addition to readability it controls the scope of the token you're defining during init. That variable is (or should be) scoped to the loop only, and be inaccessible outside of it. Helps reduce "wth just happened" debugging moments when an init goes wrong. Answer from kagato87 on reddit.com
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Statements › for
for - JavaScript | MDN - MDN Web Docs - Mozilla
The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.
🌐
Wikipedia
en.wikipedia.org › wiki › For_loop
For loop
3 days ago - The initialization is intended ... three-part for loop is a pre-test loop. They are commonly formatted in manner similar to · for initialization, condition, increment do body repeat · This syntax came from B and was originally invented by Stephen C....
Find elsewhere
🌐
Stanford
web.stanford.edu › class › archive › cs › cs106a › cs106a.1202 › handouts › py-loop.html
For Loop
Here is a for-loop example that prints a few numbers: ... Loop Syntax: the loop begins with the keyword for followed by a variable name to use in the loop, e.g. num in this example. Then the keyword in and a collection of elements for the loop, e.g.
🌐
Berkeley
pythonnumericalmethods.studentorg.berkeley.edu › notebooks › chapter05.01-For-Loops.html
For-Loops — Python Numerical Methods
A for-loop assigns the looping variable to the first element of the sequence. It executes everything in the code block. Then it assigns the looping variable to the next element of the sequence and executes the code block again.
🌐
GeeksforGeeks
geeksforgeeks.org › computer science fundamentals › for-loop-syntax
For loop Syntax - GeeksforGeeks
February 14, 2024 - Typically, you increment or decrement the variable to ensure progress toward the loop termination condition. for (initialization; condition; update) { // Code block to be executed repeatedly as long as the condition is true }
🌐
Mozilla
developer.mozilla.org › en-US › docs › Web › JavaScript › Guide › Loops_and_iteration
Loops and iteration - JavaScript - MDN Web Docs - Mozilla
A for loop repeats until a specified condition evaluates to false. The JavaScript for loop is similar to the Java and C for loop. ... The initializing expression initialization, if any, is executed. This expression usually initializes one or more loop counters, but the syntax allows an expression ...
🌐
W3Schools
w3schools.com › python › python_for_loops.asp
Python For Loops
A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).
🌐
TutorialsPoint
tutorialspoint.com › cprogramming › c_for_loop.htm
For Loop in C
All the elements (initialization, test condition, and increment) are placed together to form a for loop inside the parenthesis with the for keyword. The syntax of the for loop in C programming language ...
🌐
Cppreference
en.cppreference.com › w › cpp › language › for.html
for loop - cppreference.com
As is the case with while loop, if statement is not a compound statement, the scope of variables declared in it is limited to the loop body as if it was a compound statement. ... As part of the C++ forward progress guarantee, the behavior is undefined if a loop that is not a trivial infinite ...
🌐
University of Utah
users.cs.utah.edu › ~germain › PPS › Topics › for_loops.html
Programming - For Loop
The variable "i" below is always used as the loop counter. The variables, start_value,by_count,and finish_value all represent numbers. For each language and example of the code to sum the numbers from 1 to 10 is given. % design pattern for i = start_value:by_count:finish_value do something end % example: sum numbers from 1 to 10 total = 0; for i = 1 : 10 total = total + i; end
🌐
Mimo
mimo.org › glossary › python › for-loop
Python For Loop: Syntax and Examples [Python Tutorial]
In this example, the loop iterates over the list of numbers with a starting value of 1. Each iteration assigns the current value from the sequence of numbers to number. The function call in the code block prints each number in the list. range() is a built-in function that creates a list of numbers starting at 0 and stopping before a specified integer. This makes the range function ideal for creating Python for loops with index variables.
🌐
Study.com
study.com › computer science courses › computer science 111: programming in c
For Loop in C Programming | Definition, Syntax & Examples - Lesson | Study.com
May 17, 2019 - If it is evaluated as true again, the body will run again. If it is false, the loop will exit. The basic syntax of a for loop in C is the for statement followed by a number of control expressions separated by semi-colons:
🌐
Programiz
programiz.com › c-programming › c-for-loop
C for Loop (With Examples)
The count is initialized to 1 and the test expression is evaluated. Since the test expression count<=num (1 less than or equal to 10) is true, the body of for loop is executed and the value of sum will equal to 1.
Top answer
1 of 7
133

The comma is not exclusive of for loops; it is the comma operator.

x = (a, b);

will do first a, then b, then set x to the value of b.

The for syntax is:

for (init; condition; increment)
    ...

Which is somewhat (ignoring continue and break for now) equivalent to:

init;
while (condition) {
    ...
    increment;
}

So your for loop example is (again ignoring continue and break) equivalent to

p=0;
while (p+=(a&1)*b,a!=1) {
    ...
    a>>=1,b<<=1;
}

Which acts as if it were (again ignoring continue and break):

p=0; 
while (true) {
    p+=(a&1)*b;
    if (a == 1) break;
    ...
    a>>=1;
    b<<=1;
}

Two extra details of the for loop which were not in the simplified conversion to a while loop above:

  • If the condition is omitted, it is always true (resulting in an infinite loop unless a break, goto, or something else breaks the loop).
  • A continue acts as if it were a goto to a label just before the increment, unlike a continue in the while loop which would skip the increment.

Also, an important detail about the comma operator: it is a sequence point, like && and || (which is why I can split it in separate statements and keep its meaning intact).


Changes in C99

The C99 standard introduces a couple of nuances not mentioned earlier in this explanation (which is very good for C89/C90).

First, all loops are blocks in their own right. Effectively,

for (...) { ... }

is itself wrapped in a pair of braces

{
for (...) { ... }
}

The standard sayeth:

ISO/IEC 9899:1999 §6.8.5 Iteration statements

¶5 An iteration statement is a block whose scope is a strict subset of the scope of its enclosing block. The loop body is also a block whose scope is a strict subset of the scope of the iteration statement.

This is also described in the Rationale in terms of the extra set of braces.

Secondly, the init portion in C99 can be a (single) declaration, as in

for (int i = 0; i < sizeof(something); i++) { ... }

Now the 'block wrapped around the loop' comes into its own; it explains why the variable i cannot be accessed outside the loop. You can declare more than one variable, but they must all be of the same type:

for (int i = 0, j = sizeof(something); i < j; i++, j--) { ... }

The standard sayeth:

ISO/IEC 9899:1999 §6.8.5.3 The for statement

The statement

for ( clause-1 ; expression-2 ; expression-3 ) statement

behaves as follows: The expression expression-2 is the controlling expression that is evaluated before each execution of the loop body. The expression expression-3 is evaluated as a void expression after each execution of the loop body. If clause-1 is a declaration, the scope of any variables it declares is the remainder of the declaration and the entire loop, including the other two expressions; it is reached in the order of execution before the first evaluation of the controlling expression. If clause-1 is an expression, it is evaluated as a void expression before the first evaluation of the controlling expression.133)

Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.

133) Thus, clause-1 specifies initialization for the loop, possibly declaring one or more variables for use in the loop; the controlling expression, expression-2, specifies an evaluation made before each iteration, such that execution of the loop continues until the expression compares equal to 0; and expression-3 specifies an operation (such as incrementing) that is performed after each iteration.

2 of 7
8

The comma simply separates two expressions and is valid anywhere in C where a normal expression is allowed. These are executed in order from left to right. The value of the rightmost expression is the value of the overall expression.

for loops consist of three parts, any of which may also be empty; one (the first) is executed before the first iteration, and one (the third) at the end of each iteration. These parts usually initialize and increment a counter, respectively; but they may do anything.

The second part is a test that is executed at the beginning of each execution. If the test yields false, the loop is aborted. That's all there is to it.