English Deutsch Français Italiano Español Português 繁體中文 Bahasa Indonesia Tiếng Việt ภาษาไทย
All categories

I wrote

for (int n=0; n<10; n++ )
{
...
}


Is there an elegant way of skipping n= 6, without
writing two loops ?

2006-11-03 12:26:09 · 5 answers · asked by bergab_hase 3 in Computers & Internet Programming & Design

PS.

I don't want to do this

for(n=0; n < 10; n++ )
{
if (n != 6 )
{
...
}
}

because it executed if() function 10 times and creates slow code.

2006-11-03 12:31:36 · update #1

5 answers

I wouldn't worry about an extra if eating up any extra CPU's. Believe me, the difference would be negligible...

If you really want to speed up your code, do this:
int x = 0;
for ( ; x < 6; x++ ) {
doWork();
}

x++;
for ( ; x < 10; x++ ) {
doWork();
}

that's about as fast as it gets. It's more code bloat, but it does prevent the extra if().

2006-11-03 12:47:19 · answer #1 · answered by mchenryeddie 5 · 2 0

Did your instructor warn you about using magic number?

you have 2 magic numbers in your code: 10 and 6. There is always a way to refine your code better.

2006-11-03 20:37:53 · answer #2 · answered by Huey L 3 · 0 1

You could try this
if (n == 6)
continue;
It will continue the loop with n = 7

2006-11-03 20:29:36 · answer #3 · answered by trung thanh 2 · 2 0

if (n=6) n ++; increment the value of n then and there.

2006-11-04 01:56:07 · answer #4 · answered by manoj Ransing 3 · 0 0

while(int n=0; n<10; n++)

{
...
}

2006-11-03 20:39:53 · answer #5 · answered by alenm8816 4 · 0 2

fedest.com, questions and answers