In C, there are three main loop constructs: for, while, and do-while. Their emergence is related to the need for repeated computations, simplifying data structure traversal, and automating array processing. The syntax of loops first appeared in early programming languages (Algol, Fortran) and was adapted to C syntax for improved readability and flow control.
Background
Initially, programmers used labels and goto statements to organize repetitive actions, which quickly led to convoluted code (spaghetti code). The introduction of structured loops (in C - since 1972) allowed for a unified approach to repetition and describing program logic.
The Problem
The main task of loops is to determine how many times a specific action should be repeated and how to control the exit from the loop. It's essential to choose the loop type correctly depending on whether the number of repetitions is known in advance, if the body must execute at least once, and if the exit condition needs to be evaluated beforehand.
The Solution
Example code:
#include <stdio.h> int main() { int i = 0; // Example of a while loop while (i < 3) { printf("while: %d\n", i); i++; } // Example of a for loop for (int j = 0; j < 3; j++) { printf("for: %d\n", j); } // Example of a do-while loop int k = 0; do { printf("do-while: %d\n", k); k++; } while (k < 3); return 0; }
Key features:
What is the difference between while(1) and for(;;) and which one is better for infinite loops?
Answer: Both variants create an infinite loop and compile into the same machine code; there is no difference in performance. Typically, for(;;) is used to explicitly show that no initialization, exit condition, or step is expected.
for(;;) { // infinite loop } // or while(1) { // infinite loop }
Can you change the loop variable inside the for body and what will happen?
Answer: Changing the counter variable (for example, i++) within the for loop body will lead to unpredictable iterations. Such changes confuse readers and complicate debugging.
for (int i = 0; i < 10; i++) { printf("%d\n", i); i += 2; // non-standard step modification! }
What happens if the loop body is left empty? When is this sensible?
Answer: An empty loop body is permissible and is used for waiting for an event to occur or preparing data:
while(*src++ = *dst++); // copying a string until the '\0' character
Negative Case
In a project, for was used with the counter variable changed inside the body, leading to an incorrect number of processed elements, bugs, and difficulties in debugging.
Pros:
Cons:
Positive Case
Using for to traverse a fixed-length array without changing the counter externally:
Pros:
Cons: