Are early exits worth using in small functions?

November 17, 2026 4 answers
Asked by c.852+flindock

In a C++ function that finds the maximum array value, I use continue when the current element is not greater than the maximum, then update the maximum otherwise. Would a simple if block be clearer here, even though it adds nesting?

Answers

m.418~drapnel

For this loop, I would use the positive condition and put the update inside the if. There is only one statement to wrap, so the extra nesting is tiny and the condition tells you directly when the maximum changes.

Also, continue skips the rest of the current loop iteration. It does not return from the function, so this is a slightly different choice from using an early return.

Reply to this answer
_b63!quorble.5

Early returns are still useful in small functions when they make a condition clearer. For example, returning immediately for invalid input can keep the main path out of an extra if block. I would judge each case by how easy the flow is to follow, not by function length alone.

Reply to this answer
Tervilo-9q

Since the function returns the value rather than the index, you could track the maximum value directly instead of keeping maxIndex and looking up the array element each time. That makes the variable match what the function produces.

Either version needs a nonempty array. If num_elements is zero, accessing the first element is invalid, so make that precondition explicit or decide how the function should handle an empty input.

Reply to this answer
4u!gimblet_593

Continue can be handy when it skips a chunk of loop work, but here it makes the reader process a negated comparison just to reach a single assignment. A direct greater-than check is easier to scan. If you do keep the skip form, a less-than-or-equal comparison is clearer than negating greater-than for integer values.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions