Search code examples
c++coding-stylestandards-compliance

C++: return the return value of a void function from a void function


I have several void functions (lets call them foo and bar) that share the same void function cleanup that, well, cleans up after them if they mess up:

#include <iostream>

void cleanup() { std::cout << "doing cleanup" << std::endl; }

void foo(int & i) {
    if(i == 0) { return cleanup(); }
    --i;
    if(i == 0) { return cleanup(); }
    ++i;
}

void bar(int & i) {
    if(i == 0) { return cleanup(); }
    ++i;
    if(i == 0) { return cleanup(); }
    --i;
}

int main() {
    int i = 0;
    foo(i);
    bar(i);
    return 0;
}

cpp.sh happily compiles and runs the code.

Thanks to the answer to this question I know that I can return an object of type void. But I don't know if it applies to returning void return values.

What do you think, does the code comply with the standard?

And would you rather return dummy integers to make the code more readable? Or would the useless return values make the code harder to read?

edit: I feel like I need to add some clarification as to why e.g. 'cleanup(); return;' is not a solution. The actual code is more complex than the example and depending on where I leave the function some other stuff happens after the cleanup() call. 'return cleanup();' is just a convenient way of not putting all the stuff behind it in conditionals in instances where I can/have to leave immediately.


Solution

  • From n4582

    6.6.3 The return statement [stmt.return]

    Paragraph 2

    The expr-or-braced-init-list of a return statement is called its operand. A return statement with no operand shall be used only in a function whose return type is cv void, a constructor (12.1), or a destructor (12.4). A return statement with an operand of type void shall be used only in a function whose return type is cv void. A return statement with any other operand shall be used only in a function whose return type is not cv void; the return statement initializes the object or reference to be returned by copy-initialization (8.5) from the operand.

    Questions:

    But I don't know if it applies to returning void return values.

    Yes its perfectly valid to return a void expression from a function that return void. This becomes very handy in templated code so you don't have to special case void functions.

    What do you think, does the code comply with the standard?

    Yes absolutely.

    And would you rather return dummy integers to make the code more readable? Or would the useless return values make the code harder to read?

    That's totally up to you and your aesthetics. Does it make the code look more readable to you (or do you have coding guidelines that you need to follow). Personally I would not return dummy values (as the user may expect some meaning from them).