Returning From a Void Function in C++

前端 未结 7 1034
再見小時候
再見小時候 2020-12-31 11:21

Consider the following snippet:

void Foo()
{
  // ...
}

void Bar()
{
  return Foo();
}

What is a legitimate reason to use the above in C++

7条回答
  •  爱一瞬间的悲伤
    2020-12-31 11:59

    You would use it in generic code, where the return value of Foo() is unknown or subject to change. Consider:

    template T Bar(Foo f) {
        return f();
    }
    

    In this case, Bar is valid for void, but is also valid should the return type change. However, if it merely called f, then this code would break if T was non-void. Using the return f(); syntax guarantees preservation of the return value of Foo() if one exists, AND allows for void().

    In addition, explicitly returning is a good habit to get into.

提交回复
热议问题