-4

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
Biswajit
  • 47
  • 5
  • Possible duplicate of [C++11 range-based for loops without loop variable](https://stackoverflow.com/questions/17711655/c11-range-based-for-loops-without-loop-variable) – Epion Feb 13 '19 at 13:49
  • Why would someone want to do that? Unless initialized, it would be an infinite loop. When you want it to iterate over 4 times, let it know that way. – WedaPashi Feb 13 '19 at 13:55
  • 3
    Well you need a variable to keep the iteration count. Without a count you can only get an infinite loop. – rustyx Feb 13 '19 at 13:55
  • is loop unrolling an option ? (possibly [aided with macro's or template functions](https://stackoverflow.com/questions/28231743/self-unrolling-macro-loop-in-c-c)) – Sander De Dycker Feb 13 '19 at 14:03
  • Avoid tagging both C and C++ – Jarod42 Feb 13 '19 at 14:08
  • 5
    What problem are you _actually_ trying to resolve? This could be an [XY Problem](http://xyproblem.info) – Jabberwocky Feb 13 '19 at 14:14
  • 1
    @WedaPashi -- this would mean "do this four times", without the distraction of having to name a loop-control variable, and perhaps without the distraction of some compiler writer complaining that you created a variable that you never used. – Pete Becker Feb 13 '19 at 15:47
  • @PeteBecker: True that. But I am trying to foresee a use-case for one such implementation.. – WedaPashi Feb 14 '19 at 06:23

3 Answers3

2

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;
}

See code running on ideone

Output

foo bar bar
foo bar bar
foo bar bar
foo bar bar
pmg
  • 106,608
  • 13
  • 126
  • 198
-1

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;
}
haccks
  • 104,019
  • 25
  • 176
  • 264
-1

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);
}
Krzysiek Karbowiak
  • 1,655
  • 1
  • 9
  • 17