Freigeben über


The Inline Returns Option

Using my last example, Stuart Ballard pointed out that using inline returns is another way to avoid the uninitialized variable mistake:

 if (hwndParent != NULL) 
{ 
    if (fFoo) 
    { 
        return DoOperationWithFoo(hwndParent); 
    } 
    else if (fBar) 
    { 
        return DoOperationWithBar(hwndParent); 
    } 
} 

return whatever_the_default_return_code_should_be;

This is true, although whether to use inline returns vs. the structured programming technique of one entry point and one exit point is a separate consideration. :-)

Inline returns (and even exceptions) are usually fine as long as you are using a language with garbage collection, such as C# or Java, or you religiously adhere to the RAII technique (using smart pointers and such). However, in many programming environments where you're still manually managing resources: memory, reference counting COM objects, critical sections, registry and file handles, etc., inline returns can be dangerous. We use RAII quite a bit in our code, but not enough yet to reliably switch to the model of inline returns, so I didn't even think of mentioning that in my original post.

(There's also something to be said for being able to rewind the instruction pointer and step through code again while debugging, something that's made easy with the technique of one entry point and one exit point.)

Comments

  • Anonymous
    January 26, 2006
    Heh. It's interesting how many things there are that have to be taken into account in C++ that are so alien in the C#/Java world.

    I suppose you could say that I'm spoiled by working in a higher level language, but I prefer to think of it as being able to work at a higher level of abstraction...

    (and the thought of working without exceptions frankly scares me!)