5

Is this code legal? It compiles but I'm wondering what happens with the return value. Undefined behavior?

class Foo {
public:
    void test1() {

    }
    auto test() -> decltype(test1()) {
        return test1(); //<---return void here!
    }
};
3
  • 2
    A void function can return another void function. A void function can even return (void)"I'm a void";
    – mfnx
    Dec 31, 2019 at 9:41
  • 2
    There are rules in place in the C++ spec that allow a void function to return a void value, to handle cases where templated functions may need to do exactly that without having to use special treatment just for void Dec 31, 2019 at 10:11
  • 1
    @RemyLebeau Indeed this question came from a doubt using a template function :)
    – greywolf82
    Dec 31, 2019 at 10:29

2 Answers 2

9

The code is legal. auto deduces to void and a void function can return another void function. A void function can even

return static_cast<void>("I'm a void");
1

It's legal, but you can't, for example, assign the result to a variable. [1]

class Foo {
public:
    void test1() {

    }
    auto test() -> decltype(test1()) {
        return test1(); //<---return void here!
    }
};

int main() {
    Foo foo;
    auto x = foo.test(); //<---compile error here
}

[1] https://godbolt.org/z/YGAtdJ

1
  • 1
    I guess this should be obvious, as you cannot have a void x = whatever(); anyway [?]
    – MacDada
    Feb 14 at 1:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.