-7

Is this ever valid? Will the project compile? I do not have access to a compiler right now, but my friend had this in his code:

int returnTwice () {
  return 1;
  return 2;
}

Why and how is this inappropriate?

Thank you!

Thank you everyone that had something constructive to say.

4 Answers4

4

It's partly valid.

The invalid part is that you try to declare a variable in an expression, which is not allowed. But there's nothing illegal by having multiple unconditional return statements, however only the first will be executed.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
0

No, this isn't possible in C++ or any other programming language that I know of.

As another user who answered your question said, only the first return statement will be executed. Depending entirely on the compiler, it might give you an error or warning that you have two return functions in one defined scope, there is no syntax error here.

It is possible to return two or more values in C++ by placing each variable into a vector and returning it, as documented in this question.

A return returns the value assigned to it and exits the function.

In other programming languages such as Lua a return variable1, variable2; can be used.

Community
  • 1
  • 1
AStopher
  • 4,207
  • 11
  • 50
  • 75
  • 1
    It is also the case in Python (more popular than Lua in my opinion). – Caduchon Nov 20 '14 at 17:42
  • @Caduchon I believe that `return`ing in this way is supported in most 'raw' languages, `PHP` definitely does and I think `Java` does too. – AStopher Nov 20 '14 at 21:20
0

It's not possible in C++. But, if you want a similar behaviour, you can use boost::tuple.

boost::tuple<double,double> figInfo(const Figure& fig)
{
  double p = fig.getPerimeter();
  double s = fig.getSurface();
  return boost::make_tuple(p,s);
}

boost::tuple<std::string, unsigned short int, std::string> profile()
{
  std::string first_name = "Christophe";
  unsigned short int age = 29;
  std::string address = "Unspecified";
  return boost::make_tuple(first_name, age, address);
}
Caduchon
  • 4,574
  • 4
  • 26
  • 67
-3

When a function returns, it stops executing. Everything after the first return executed will never get executed. Thus, you should get an "Error: unreachable code" for such a function.

DaaaahWhoosh
  • 369
  • 1
  • 4
  • 15