The stylistic question of the return of emptiness

Consider the following contrived example:

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

This code works very well, and I'm sure it is specified, but I (perhaps by myself) consider this unusual style, as the call seems to return the result of the function, despite the fact that both functions are prototyped as invalid.

Typically, I expect to see:

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

which, I feel, leaves no ambiguity as to what is happening.

SO community, can I express your opinion on the confusing or problematic coding style of return-void? It has a sense of idiom; should this be used or avoided?

In general, I would strive for clarity and use a second style. On the other hand, there is accuracy in the first form, which attracts me a little.

+5
c ++ idioms coding-style
Aug 6 '09 at 19:28
source share
5 answers

I agree with you, the first style is confusing, because it implies that some value is returned. Because of this, I had to read it several times.

When returning from the prototyped void function, it must be returned,

+13
Aug 06 '09 at 19:31
source share

This is probably just too smart. If this line ends more than a couple lines from the top of the function, this will be confused. It also means that the programmer looking at the code will have to relate

 return HandleThat(); 

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

 if (That) { HandleThat(); return; } 
+11
Aug 06 '09 at 19:33
source share

C language rules say that 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

+4
Aug 6 '09 at 19:36
source share

Never seen this before.

This has the advantage of looking like a normal idiom for non-imaginary return types, so it reads very easily ...

I would not change it if someone cannot show that it is invalid.

+3
Aug 6 '09 at 19:33
source share

I believe that the first version basically makes it easier to program templates. If HandleThat returns a type T, which may or may not be invalid, it is convenient to use the first version.

But in "normal" cases, the second version is understandable, and I would prefer that.

+2
Aug 6 '09 at 21:10
source share



All Articles