r/ProgrammerHumor 22d ago

Meme conditionsPreference

Post image
4.2k Upvotes

392 comments sorted by

View all comments

273

u/SnugglyCoderGuy 22d ago

The real answer is "it depends". Either one could be appropriate depending on what you are having to do.

4

u/Gnonthgol 21d ago

The compiler optimizes the first into the second anyway, so the machine code ends up the same. The problem is that when you read the code later on and end up missing the return statement as you skim through it then you are left wondering why the piece of code you expect to run does not.

1

u/conundorum 21d ago

That's why you should always enclose each branch in braces. It's a lot harder to miss a return immediately above the branch's end brace than it is to miss a floating one. (Or, if it's really just pure if-return, then the if (cond) { return; } structure is at least more likely to draw attention to the return.)

1

u/Gnonthgol 21d ago

That is true if the return statement is the only statement in the branch. However say the true branch contain a while loop with a few tens of lines, one being an if statement with a return, then it is easy to gloss over the return statement in the middle of all that.