simple question regarding C++ code:
for(int i=0;i<npts;i++)
{
for(int j=i;j<2*ndim;j++)
{
if(funcEvals[i]<bestListEval[j])
{
bestListEval[j] = funcEvals[i];
for(int k=0;k<m_ndim;k++)
bestList[j][k] = simplex[i][k];
break;
}
}
}
I want to ensure that
double **simplex
is inserted at most once in double **bestList
break
here breaks out of the second (inner) for
loop.Is this the case?
Therefore, break applies to only the loop within which it is present. Infinite Loops: break statement can be included in an infinite loop with a condition in order to terminate the execution of the infinite loop.
Using break in a nested loop In a nested loop, a break statement only stops the loop it is placed in. Therefore, if a break is placed in the inner loop, the outer loop still continues. However, if the break is placed in the outer loop, all of the looping stops.
The break statement is used inside loops or switch statement. The break statement breaks the loop one by one, i.e., in the case of nested loops, it breaks the inner loop first and then proceeds to outer loops.
When a break statement is encountered inside a loop, the loop is immediately terminated and the program control resumes at the next statement following the loop. It can be used to terminate a case in the switch statement (covered in the next chapter).
The break
statement in C++ will break out of the for
or switch
statement in which the break
is directly placed. In this case it will break out of the for (int j = ...
loop.
There is no way in C++ to have break
target any other loop. In order to break out of parent loops you need to use some other independent mechanism like triggering the end condition.
// Causes the next iteration of the 'for (int i ...' loop to end the loop)
i = npts;
// Ends the 'for (int j ...' loop
break;
The break statement in C++ will break out of the for or switch statement in which the break is directly placed. It breaks the innermost structure (loop or switch). In this case:
for(int i=0;i<npts;i++)
{
for(int j=i;j<2*ndim;j++)
{
if(funcEvals[i]<bestListEval[j])
{
bestListEval[j] = funcEvals[i];
for(int k=0;k<m_ndim;k++)
bestList[j][k] = simplex[i][k];
break;
}
}
// after the 'break' you will end up here
}
There is no way in C++ to have break target any other loop. In order to break out of parent loops you need to use some other independent mechanism like triggering the end condition.
Also, if you want to exit more than one inner-loop you can extract that loops into a function. In C++ 11 lambdas can be used to do it in-place - so there will be no need to use goto.
You are breaking out of your second loop to your first loop.
for (int i=0; i<npts; i++)
You could set a boolean at the top
bool shouldBreak = false;
and when you write break, write
shouldBreak = true;
break;
Then at the end of your loop, check each time,
if (shouldBreak) break;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With