I want to write a for loop directly without any variable. Is it possible?
Example:
for (1; 1 <= 4; ++) {
printf ("Loop working\n");
}
Expected output:
Loop working
Loop working
Loop working
Loop working
I want to write a for loop directly without any variable. Is it possible?
Example:
for (1; 1 <= 4; ++) {
printf ("Loop working\n");
}
Expected output:
Loop working
Loop working
Loop working
Loop working
You need a variable to keep count, but you can hide it.
#include <stdio.h>
#define JOIN(a, b) (a ## b)
// WARNING: don't LOOP in the same line
#define LOOP(n) for (unsigned JOIN(HIDDEN, __LINE__) = 0; JOIN(HIDDEN, __LINE__) < n; JOIN(HIDDEN, __LINE__)++)
int main(void) {
LOOP(4) {
printf("foo");
LOOP(2) printf(" bar");
puts("");
}
return 0;
}
Output
foo bar bar foo bar bar foo bar bar foo bar bar
Yes, it is possible.
for(; ;);
But this will be an infinite loop. Add a break statement and it will run only once
for(; ; )
break;
Or you can use increment and conditional statements inside the loop
int i = 0;
for(; ;){
printf ("Loop working\n");
++i;
if( i >= 4)
break;
}
To have the loop terminate, you need to keep state which says at which point you are.
Usually, you use loop variable for this.
You can also use recursion, in which case the state is encoded differently, but still needed:
void loop(int i)
{
if (i < 4) {
printf ("Loop working\n");
loop(++i); // recursive call
}
}
int main()
{
loop(0);
}