Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Repeat a block of code a fixed number of times

I'm trying to repeat a block of code, without using a condition, yet still only repeating it a specific number of times.

Basically, something like this:

repeat(50)
{
    //Do stuff here.
}

Is there a way to do this? Other than copying and pasting 50 times?

I'm doing this because I figured if I know how many times I want to repeat something, it'd be quicker than checking a condition every time. Is that accurate? Or would I still be checking how many times it's been repeated?

Basically, is it any faster at all?

like image 957
Serdnad Avatar asked Apr 28 '13 22:04

Serdnad


1 Answers

If you want the syntactic nicety of being able to write repeat(x) {} then you could use a macro.

Something like:

#include <iostream>

#define repeat(x) for(int i = x; i--;)

int main()
{
    repeat(10) 
    {
        std::cout << i << std::endl;
    }

    return 0;
}

The implementation here also uses a comparison to zero in the for loop rather than the less than operator, which may be slightly faster.

like image 131
j b Avatar answered Sep 23 '22 00:09

j b