What is the most elegant way to loop TWICE in C

Viewed 18487

Many times I need to do things TWICE in a for loop. Simply I can set up a for loop with an iterator and go through it twice:

for (i = 0; i < 2; i++)
{
 // Do stuff
}

Now I am interested in doing this as SIMPLY as I can, perhaps without an initializer or iterator? Are there any other, really simple and elegant, ways of achieving this?

24 Answers

As Edsger W. Dijkstra himself put it : "two or more, use a for". No need to be any simpler.

I like Chris Case's solution (up here), but C language doesn't have default parameters.

My solution:

bool cy = false;
do {
    // Do stuff twice
} while (cy = !cy);

If you want, you could do different things in the two cycle by checking the boolean variable (maybe by ternary operator).

Related