3 ms·
At my first programming job they were religious about the single `return' and followed a pattern that was bizarre and luckily I've not seen since--using a `retV
by gav 4y ago
At my first programming job they were religious about the single `return' and followed a pattern that was bizarre and luckily I've not seen since--using a `retVal' variable declared at the top.
int foo(int bar) {
int retVal = -1;
if (bar == 1) {
retVal = 1;
}
if ((retVal % 2) == 0) {
retVal = 2;
}
return retVal;
}
- ehvatum 4y agoIt might have improved in the last few years, but as of 2018, MSVC would not do named value return optimization for the case where all branches returned the same local variable, in my experience. There had to be just the one penultimate return statement, in order for NRVO to kick in.
- mlvljr 4y ago[dead]
- gymbeaux 4y agoMost of my teammates are in Serbia and I see naming the return object "toReturn" a lot... so yes, the code reads "return toReturn;"
- JohnFen 4y agoYes, I've seen this a lot over the years. Also, putting code inside a do ... while( false ) loop purely so you can use break as a sneaky goto to avoid deeply nested conditionals while technically adhering to the single return rule. I think when you're starting to use control statements in bizarre ways like that, it's a good indication that maybe that's a case where breaking the "rules" is the best thing.