C doesn't have a foreach, but macros are frequently used to emulate that:

#define for_each_item(item, list) \
    for(T * item = list->head; item != NULL; item = item->next)

And can be used like

for_each_item(i, processes) {
    i->wakeup();
}

Iteration over an array is also possible:

#define foreach(item, array) \
    for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
        keep && count != size; \
        keep = !keep, count++) \
      for(item = (array) + count; keep; keep = !keep)

And can be used like

int values[] = { 1, 2, 3 };
foreach(int *v, values) {
    printf("value: %d\n", *v);
}

Edit: In case you are also interested in C++ solutions, C++ has a native for-each syntax called "range based for"

Answer from Johannes Schaub - litb on Stack Overflow
Top answer
1 of 15
227

C doesn't have a foreach, but macros are frequently used to emulate that:

#define for_each_item(item, list) \
    for(T * item = list->head; item != NULL; item = item->next)

And can be used like

for_each_item(i, processes) {
    i->wakeup();
}

Iteration over an array is also possible:

#define foreach(item, array) \
    for(int keep = 1, \
            count = 0,\
            size = sizeof (array) / sizeof *(array); \
        keep && count != size; \
        keep = !keep, count++) \
      for(item = (array) + count; keep; keep = !keep)

And can be used like

int values[] = { 1, 2, 3 };
foreach(int *v, values) {
    printf("value: %d\n", *v);
}

Edit: In case you are also interested in C++ solutions, C++ has a native for-each syntax called "range based for"

2 of 15
17

As you probably already know, there's no "foreach"-style loop in C.

Although there are already tons of great macros provided here to work around this, maybe you'll find this macro useful:

// "length" is the length of the array.   
#define each(item, array, length) \
(typeof(*(array)) *p = (array), (item) = *p; p < &((array)[length]); p++, (item) = *p)

...which can be used with for (as in for each (...)).

Advantages of this approach:

  • item is declared and incremented within the for statement (just like in Python!).
  • Seems to work on any 1-dimensional array
  • All variables created in macro (p, item), aren't visible outside the scope of the loop (since they're declared in the for loop header).

Disadvantages:

  • Doesn't work for multi-dimensional arrays
  • Relies on typeof(), which is a GNU extension, not part of standard C
  • Since it declares variables in the for loop header, it only works in C11 or later.

Just to save you some time, here's how you could test it:

typedef struct {
    double x;
    double y;
} Point;

int main(void) {
    double some_nums[] = {4.2, 4.32, -9.9, 7.0};
    for each (element, some_nums, 4)
        printf("element = %lf\n", element);

    int numbers[] = {4, 2, 99, -3, 54};
    // Just demonstrating it can be used like a normal for loop
    for each (number, numbers, 5) { 
        printf("number = %d\n", number);
        if (number % 2 == 0)
                printf("%d is even.\n", number);
    }

    char* dictionary[] = {"Hello", "World"};
    for each (word, dictionary, 2)
        printf("word = '%s'\n", word);

    Point points[] = {{3.4, 4.2}, {9.9, 6.7}, {-9.8, 7.0}};
    for each (point, points, 3)
        printf("point = (%lf, %lf)\n", point.x, point.y);

    /* Neither p, element, number or word are visible outside the scope of
    their respective for loops. Try to see if these printfs work (they shouldn't): */
    //printf("*p = %s", *p);
    //printf("word = %s", word);

    return 0;
}

Seems to work on gcc and clang by default; haven't tested other compilers.

๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c++ โ€บ g-fact-40-foreach-in-c-and-java
Foreach in C++ and Java - GeeksforGeeks
July 23, 2025 - There is no foreach loop in C, but both C++ and Java support the foreach type of loop.
Discussions

foreach loop in C/C++
Be careful about this kind of language customization. It may seem fine to you when you're just working on the program by yourself, but as soon as you have to work with other programmers, you're going to run into readability problems. Imagine if every programmer created their own set of "helpful" macros. Joe wants his C++ to look like Python, Bob prefers Perl, and Alice just invented her own keywords replacements entirely. What a mess! It's much better to just learn the language as-is and use standard libraries and constructs. That's not too say you can't create your own ease of use macros and helper functions, but I'd draw the line at drop-in replacements for the language's intended syntax and keywords. More on reddit.com
๐ŸŒ r/Cplusplus
7
3
March 22, 2016
Doing generic foreach loops in C
Why not: #define ARRSIZE(arr) (sizeof (arr) / sizeof *(arr)) #define foreach(item, list) \ for(__typeof__ (*(list)) item, *_cur = (list), *_end = _cur + ARRSIZE(list); \ _cur != _end ? (item = *_cur), 1 : 0; \ ++_cur) Now one can do: int main(int argc, char *argv[]) { int i[] = { 2, 5, 7, 8, 10, 12 }; // 6 elements char *s[] = { "one", "two", "three" }; // 3 elements foreach(g, i) printf("%u\n", g); foreach(g, s) printf("%s\n", g); return 0; } Try godbolt . Works well with compound literals: foreach(g, ((int[]){ 1, 2, 3 })) printf("%d\n", g); More on reddit.com
๐ŸŒ r/cprogramming
5
2
April 14, 2023
how to make a for loop?
The syntax: for (initial statement; loop condition; repeating statement) The initial statement is a statement that runs before the whole thing start once, and the thing with it is that the initial statement can be any statement. You can declare a local variable, run a function, etc. It can be any single statement. The condition is the conditional that gets checked before each ... More on reddit.com
๐ŸŒ r/cprogramming
9
0
February 16, 2023
When to use a for loop and when to use a while loop?
Short answer: Use what make sense. I am not sure what language you are speaking, but if it's English then follow how you phrase what you want to do in your head. If in your head you say, "let's go from 0 to the end" use for( int i =0; i < arr.lenght; i++) {..} If you say in your head, "Let's do it while we can" use while( rd.MoveNext() ) {..} More on reddit.com
๐ŸŒ r/csharp
43
26
August 1, 2022
People also ask

Why is "for loop" used in C programming?
For loops are used in C, as in other programming languages, facilitating the execution of a code block a specified number of times by assessing a condition as either true or false. This construct can contain further statements, including other for statements or compound statements.
๐ŸŒ
study.com
study.com โ€บ computer science courses โ€บ computer science 111: programming in c
For Loop in C Programming | Definition, Syntax & Examples - Lesson ...
How does the "for loop" work?
The for loop in C first evaluates the initialization expression. If it evaluates true, the first iteration of the loop will run, if false the loop will not run. The code within the loop will executed and then the loop will be updated by the loop expression and re-evaluated. If it is evaluated as true again, the body will run again. If it is false, the loop will exit.
๐ŸŒ
study.com
study.com โ€บ computer science courses โ€บ computer science 111: programming in c
For Loop in C Programming | Definition, Syntax & Examples - Lesson ...
How do computer programmers write a "for loop"?
The basic syntax of a for loop in C is the for statement followed by a number of control expressions separated by semi-colons: ยท for (A; B; C) ยท { ยท body ยท } ยท A = init-expression - the expression that will be used in the first evaluation ยท B = cond-expression - the expression that will be used to evaluate whether the loop should run again or exit ยท C = loop-expression - this updates the variable for each iteration of the loop ยท The body is the block of code that will run as long as the cond-expression is true.
๐ŸŒ
study.com
study.com โ€บ computer science courses โ€บ computer science 111: programming in c
For Loop in C Programming | Definition, Syntax & Examples - Lesson ...
๐ŸŒ
GitHub
gist.github.com โ€บ 632544
Foreach loop in C ยท GitHub
Foreach loop in C. GitHub Gist: instantly share code, notes, and snippets.
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 739669 โ€บ foreach-loop-in-c
Foreach loop in C | Sololearn: Learn to code for FREE!
hi guys, i'm trying to make a foreach loop in C, i wrote it two times (lines 6 and 9), but the first loop doesn't work correctly, if i decommented it, it gives me "no output". the second loop is the same of first's except i wrote a statement out of the loop, why only second one work well?
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ c-loops
Loops in C - GeeksforGeeks
December 6, 2025 - Let's discuss all 3 types of loops in C one by one. for loop is an entry-controlled loop, which means that the condition is checked before the loop's body executes.
๐ŸŒ
W3Schools
w3schools.com โ€บ c โ€บ c_for_loop.php
C For Loop
Statement 2 defines the condition for the loop to run: i < 5. If the condition is true, the loop will start over again, if it is false, the loop will end. Statement 3 increases a value each time the code block in the loop has been executed: i++
Find elsewhere
๐ŸŒ
DigitalOcean
digitalocean.com โ€บ community โ€บ tutorials โ€บ foreach-loop-c-plus-plus
C++ foreach Loop: Modern Patterns and AI-Optimized Code | DigitalOcean
August 18, 2025 - This powerful iteration construct simplifies traversal over iterable data sets by eliminating the need for manual iterator management. The foreach loop automatically iterates through each element of a container, making your code more readable, maintainable, and less prone to errors compared ...
๐ŸŒ
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 - The basic syntax of a for loop in C is the for statement followed by a number of control expressions separated by semi-colons: ... B = cond-expression - the expression that will be used to evaluate whether the loop should run again or exit ยท ...
๐ŸŒ
Udemy
blog.udemy.com โ€บ home โ€บ introduction to for loop c: how to repeat code blocks with the for() loop
Introduction to For Loop in C with Examples - Udemy Blog
February 16, 2022 - The design of a for() loop is such that it begins with a single proposition (such as count = 1) and then continues to loop until a condition is met (such as count = 25). While the loop continues, a certain action is taken (such as incrementing ...
๐ŸŒ
Reddit
reddit.com โ€บ r/cplusplus โ€บ foreach loop in c/c++
r/Cplusplus on Reddit: foreach loop in C/C++
March 22, 2016 -

So I've been using C a lot lately, and I've found myself using the construct

for(int i=0; i<some_count; i++) { 
     /* operation */ 
}

So I created a macro that wraps that up into a special foreach loop:

#define foreach(var, condion) \
for(int var=0; var<condition; var++)

I use it just as one would expect:

foreach(i, some_count) {
     /* operation */
}

Is this safe? I have had no issues in my code, so I can't imagine why this would cause any problems. But since I encounter very few other examples of this on the web, I wonder if there is a good reason why this doesn't appear.

Addition:

I have also created macros for perl-style keywords. I don't use them much, but I like that they're available.

#define until(expr)     while(!(expr))
#define unless(expr)    if(!(expr))
#define elif(expr)      else if(expr)

Is there anything wrong with these? They all work perfectly fine, but somehow it feels "dirty" or "impure" to do this in C.

๐ŸŒ
Medium
medium.com โ€บ @Dev_Frank โ€บ for-loop-in-c-language-7f59576d990d
FOR LOOP IN C LANGUAGE | by Dev Frank | Medium
January 14, 2024 - FOR LOOP IN C LANGUAGE In C programming, loop statements are used to repeatedly execute a block of code until a certain condition is met. The three main types of loops in C are: 1. for loop 2. while โ€ฆ
๐ŸŒ
DEV Community
dev.to โ€บ sgf4 โ€บ foreach-macro-in-c-48ic
Foreach macro in C - DEV Community
May 6, 2023 - FOREACH_X will call recursively until reach FOREACH_1, every call will recursively grab the first argument and forward the rest to the next function always callling to FN macro.
๐ŸŒ
Reddit
reddit.com โ€บ r/cprogramming โ€บ doing generic foreach loops in c
r/cprogramming on Reddit: Doing generic foreach loops in C
April 14, 2023 - C++ is a high-level, general-purpose programming language first released in 1985. Modern C++ has object-oriented, generic, and functional features, in addition to facilities for low-level memory manipulation. ... A 'foreach' loop for the preprocessor, without boilerplate and supporting arbitrarily long sequences
๐ŸŒ
Unstop
unstop.com โ€บ home โ€บ blog โ€บ for loop in c explained with detailed code examples
For Loop In C Explained With Detailed Code Examples
January 12, 2024 - After each iteration, the value of i is incremented by 1. We begin with sum=0, which after 1st iteration becomes, sum= 0+1 =1, after 2nd iteration sum = 1+2 =3, after 3rd iteration sum = 3+3=6, and so on. The printf() statement inside the loop consists of a formatted string, which prints the iteration number (i) and the current sum.
๐ŸŒ
Programiz
programiz.com โ€บ c-programming โ€บ c-for-loop
C for Loop (With Examples)
Since 2 is also less than 10, the test expression is evaluated to true and the body of the for loop is executed. Now, sum will equal 3. This process goes on and the sum is calculated until the count reaches 11. When the count is 11, the test expression is evaluated to 0 (false), and the loop terminates. Then, the value of sum is printed on the screen. We will learn about while loop and do...while loop in the next tutorial.
๐ŸŒ
Tutorialspoint
tutorialspoint.com โ€บ cplusplus โ€บ cpp_foreach_loop.htm
Foreach Loop in C++
Foreach loop is also known as range-based for loop, it's a way to iterate over elements through a container (like array, vector, list) in a simple and readable manner without performing any extra performance like initialization, increment/decrement, ...
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ c language โ€บ c-for-loop
C for Loop - GeeksforGeeks
Updation: This step is used to update the loop control variable and is executed after each iteration. body: The body of the loop are the set of statements that are executed when the condition is true. Note: As we can see, unlike the while loop and doโ€ฆwhile loop, the for loop contains the initialization, condition, and updating statements for loop as part of its syntax.
Published ย  October 8, 2025
๐ŸŒ
W3Schools
w3schools.com โ€บ cpp โ€บ cpp_for_loop_foreach.asp
C++ The foreach Loop (Ranged for-loop)
C++ Examples C++ Real-Life Examples ... loop" (also known as ranged-based for loop), which is used to loop through elements in an array (or other data structures):...
๐ŸŒ
Codeforwin
codeforwin.org โ€บ home โ€บ loop programming exercises and solutions in c
Loop programming exercises and solutions in C - Codeforwin
July 20, 2025 - These task in C programming is handled by looping statements. Looping statement defines a set of repetitive statements. These statements are repeated with same or different parameters for a number of times.
๐ŸŒ
Log2Base2
log2base2.com โ€บ C โ€บ loop โ€บ for-loop-in-c.html
for loop in c
Here we exactly know the loop iteration count which is 10. ... Here also we know the iteration count exactly which is 100. for (initialize; condition; increment or decrement) { //statements }