I'm new to C++. I have the following form of code. I was wondering how I could rewrite this without the use of goto. If I use break in place of it, then I still check the if statement following the loop on every pass through this code even though if I did break I know this condition will fail, so why check it? The only solution I was able to come up with is to make this code a function and replace the goto with a return and remove the if conditional following the loop, leaving just the statements. Would this be a place where goto IS acceptable?
Edit: I should also mention the reason I leave the loop when we find an equal member, is because I don't need to check the remainder of the members in my object cause I already know the one we found is unique to the objects we are iterating, therefore there will never be a match if we continued through the rest of the iterators. So I just exit the loop then.
while (begIt != endIt)
if ((*begIt).member == someObject.member){
// Do these statements
goto someLabel; // then goto someLabel
}
++begIt;
}
if (begIt == endIt){ // We must have not found an equal member
// So do these statements
}
someLabel: // ...
while (true)
if (begIt == endIt){ // We must have not found an equal member
// So do these statements
break;
}
if ((*begIt).member == someObject.member){
// Do these statements
break;
}
++begIt;
}
// someLabel: ...
The only solution I would accept in my code. (or seperate function. directly executing a lambda for this is ugly...)
But it is very likely that you are worrying about the wrong things. Inserting a goto will probably not increase performance because the thing that you are intending to "optimize away" is a single conditional (pointer == pointer) which is negligible in 99.9999999% of all programs out there. So even if you are writing high-performance numerical code I would advice you to simple break and check with an if after the loop (I dare you to show me some profiler output to prove me wrong ;)
)