I have a “MyFunction” I keep obsessing over if I should or shouldn’t use goto on it and in similar (hopefully rare) circumstances. So I’m trying to establish a hard-and-fast habit for this situation. To-do or not-to-do.
int MyFunction()
{ if (likely_condition)
{
condition_met:
// ...
return result;
}
else /*unlikely failure*/
{ // meet condition
goto condition_met;
}
}
I was intending to net the benefits of the failed conditional jump instruction for the likely case. However I don’t see how the compiler could know which to streamline for case probability without something like this.
- it works right?
- are the benefits worth the confusion?
- are there better (less verbose, more structured, more expressive) ways to enable this optimization?
A modern CPU will take that branch either way with equal performance if it makes the correct branch prediction. So if that is in an inner loop, the performance of
if (unlikely) { meet condition } common code;will match what you have written.Also, if you spell out the common code in both branches the compiler will generate code that is identical to what you have written: The common case will be emitted for the
ifclause and theelseclause willjmpto the common code. You see this all the time with simpler terminal cases like*out = whatever; return result;. When debugging it can be hard to tell whichreturnyou’re looking at because they’ve all been merged.