Question

Consider the following contrived example:

void HandleThat() { ... }

void HandleThis()
{
    if (That) return HandleThat();
    ...
}

This code works just fine, and I'm fairly sure it's spec-valid, but I (perhaps on my own) consider this unusual style, since the call appears to return the result of the function, despite the fact that both functions are prototyped to be void.

Typically, I would expect to see:

if (That) {HandleThat(); return;}

which, I feel, leaves no ambiguity as to what's going on.

SO community, can I get your opinion on whether the returning-void coding style is confusing or problematic? It has the feel of an idiom; should I use this or avoid it?

Generally I'd strive for clarity and use the second style. On the other hand, there's a neatness to the first form that draws me to it somewhat.

Was it helpful?

Solution

I agree with you, the first style is confusing because there's the implication that some sort of value is getting returned. In fact I had to read it over a couple times because of that.

When returning from a function prototyped void, it should just be return;

OTHER TIPS

This is probably just a little too clever. If that line ends up more than a couple of lines away from the top of the function, it'll be confusing. It also means the programmer looking at the code will need to correlate the

return HandleThat();

with the void return type and figure out the cleverness before they really understand the code. When you're doing more than one thing in an if/else branch, you should really use braces and put the steps on different lines. Takes up more space but is easier to understand:

if (That) {
    HandleThat();
    return;
}

The C language rules say if a function declared as returning void tries to return an expression, the expression will not be evaluated.

http://c0x.coding-guidelines.com/6.8.6.4.html

Never seen that before.

It has the advantage of looking like a common idiom for non-void return types, so it reads very easily...

I wouldn't change it unless someone can show that it is invalid.

I believe that the first version is mainly allowed to ease template programming. If HandleThat returned a type T which might or might not be void, it's convenient to use the first version.

But in "normal" cases, the second version is clearer and I'd prefer that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top