Home > database >  Is it valid to omit the return statement of a non-void function template that throw
Is it valid to omit the return statement of a non-void function template that throw

Time:03-14

I am learning C using the resources listed here. In particular, i read about exceptions and want to know if is it valid to omit the return statement of a non-void function/function template that throw as shown below:

Example 1

#include <iostream>
//this function template does not have a return statement
template<typename T>
T func()
{
    int x = 4;
    std::cout<<"x: "<<x<<std::endl;
    throw;
}

int main()
{
  func<double>();
}

Example 2

#include <iostream>
//this function does not have a return statement
int func()
{
    int x = 4;
    std::cout<<"x: "<<x<<std::endl;
    throw;
}

int main()
{
  func();
}

My question is that are example 1 and example 2 valid? Or we have UB/ill-formed.

CodePudding user response:

are example 1 and example 2 valid?

Yes.

Or we have UB/ill-formed.

No.

Is it valid to omit the return statement of a non-void function/function template that throw

Yes. A non-void returning function must either throw or return avalue. It cannot do both at the same time.

So is int func(){ int x = 4; throw; return x;} valid

It's valid. But it never returns a value. Everything after the throw is dead code.

  • Related