0

In ruby, I have seen the following.

10.times { 
    # do this block 10 times
}

With this, (as far as I know, which is not much relative to ruby) there is no loop iterator. In C based languages, the closest replica I can come up with is a simple for loop.

for (int i = 0; i < 10; i++) {
    // do this block 10 times
}

But this utilizes the loop iterator, i. Is there any way in C based languages (including those listed in the tags) to execute a block of code a multiple number of times without the use of an iterator?
For example: If I wanted to execute a block a certain number of times, but did not care which iteration I was on.

Brian Tracy
  • 6,801
  • 2
  • 33
  • 48
  • 3
    You're misunderstanding the meaning of the word "iterator". – SLaks Apr 04 '14 at 21:20
  • 1
    You can use a macro to repeat any code any number of times known at preprocessing time. There is *sometimes* a need for that, and so as I recall the Boost preprocessor library offers this functionality. But why do you want it? – Cheers and hth. - Alf Apr 04 '14 at 21:30
  • `#define TIMES(n) for(int _i=0;_i<(n);++_i)` – BLUEPIXY Apr 04 '14 at 21:38
  • 1
    ```#define NTimes(N) for (uint32_t __ntimes_i = 0; __ntimes_i < N; __ntimes_i++)``` ```#define DO(BLOCK) BLOCK``` ```NTimes(5) DO({``` ```/// stuff``` ```})``` – CodaFi Apr 04 '14 at 21:38
  • 1
    In this context, i is actual an iteration counter. You need the counter so you know when you have done. – mjs Apr 04 '14 at 22:41

2 Answers2

3

No, this is not possible. i exists because you need to keep track of how many iterations you have performed. Even Ruby must do this under the hood, or else how would it know how many iterations had been performed?

All it really is is a difference in syntax. Ruby hides it from you where as C derivatives do not.

ProgrammingLlama
  • 36,677
  • 7
  • 67
  • 86
1

In Ruby, all types (including integers) are essentially complex types while it is common in other languages that integers are plain old primitive types. In C# for instance, as much as I don't think I would ever want to do this but if the the goal is purely that of mimicking Ruby syntax then...

Define an extension method on int

public static class Helpers
{
    public static void Times(this int value, Action action)
    {
        for (int i = 0; i < value; i++)
        {
            action.Invoke();
        }
    }
}

Do something...

10.Times(() => { ... });
blins
  • 2,515
  • 21
  • 32