Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stylistic question concerning returning void

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.

like image 694
Dave Gamble Avatar asked Aug 06 '09 19:08

Dave Gamble


4 Answers

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;

like image 130
Kevin Laity Avatar answered Sep 23 '22 20:09

Kevin Laity


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;
}
like image 26
Harold L Avatar answered Sep 22 '22 20:09

Harold L


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

like image 25
sylvanaar Avatar answered Sep 24 '22 20:09

sylvanaar


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.

like image 23
dmckee --- ex-moderator kitten Avatar answered Sep 24 '22 20:09

dmckee --- ex-moderator kitten