Is returning void valid code?

后端 未结 4 1533
时光说笑
时光说笑 2020-12-01 13:29

I found out that the following code gets accepted by Visual C++ 2008 and GCC 4.3 compilers:

void foo()
{

}

void bar()
{
  return foo();
}

4条回答
  •  [愿得一人]
    2020-12-01 14:22

    Yes, it is valid code. This is necessary when you have template functions so that you can use uniform code. For example,

    template
    T f(int x, P y)
    {
      return g(x, y);
    }
    

    Now, g might be overloaded to return void when the second argument is some particular type. If "returning void" were invalid, the call to f would then break.

提交回复
热议问题