-3

I have a question related to function without return statement at the end of definition. How it works? It can return something becouse the value to return is allocated on the stack with random number when we call the func? Check the example below:

#include <iostream>

using namespace std;

int fun1(){
    cout << "Fun1" << endl;
}

char fun2(){
    cout << "Fun2" << endl;
}

short fun3(){
    cout << "Fun3" << endl;
}

float fun4(){
    cout << "Fun4" << endl;
}

double fun5(){
    cout << "Fun5" << endl;
}

int main()
{

   cout << fun1() << " " << endl;
   cout << fun2() << " " << endl;
   cout << fun3() << " " << endl;
   cout << fun4() << " " << endl;
   cout << fun5() << " " << endl;
}
  • 2
    It's just UB. See [What happens when a function that returns an object ends without a return statement](http://stackoverflow.com/questions/39118324/what-happens-when-a-function-that-returns-an-object-ends-without-a-return-statem/39118529#39118529). – songyuanyao Sep 13 '16 at 06:56
  • For an individual function it is not an error if it always throws an exception and never reaches the end. – Bo Persson Sep 13 '16 at 07:29
  • For any function other than main (), it is fine to return from the function by reaching to the end. It is undefined behaviour to use the result of the function. So double x = fun5(); is undefined behaviour; just fun5 (); is fine. main () is an exception, it behaves as if you returned 0. @BoPersson: No exception is thrown, that's nonsense. – gnasher729 Sep 13 '16 at 07:56

1 Answers1

-5

In order to create a function without any return statements, you need to make it a "void" function. Remember that the variable types used to define the function are the type of variable that will be returned at the end of a function. If your function is Int type, it expects an Integer in return. If your function is a Char type, it expects a Character in return.

The above example won't work because in each case, the compiler is expecting a Return at the end of the function. But the functions will work if you have "void int" before each function name, like so.

void int fun1()
{
     cout << "Fun1" << end;
}
Daniel.D
  • 1
  • 1
  • You misunderstood the question. It can work with certain compilers that you specify a return value but never return anything. – Hayt Sep 13 '16 at 07:33
  • I'm using Visual Studio 2015 and creating a function that is not Void without a Return instruction will return an error. It strikes me as odd that the compiler would actually not give some sort of build error. – Daniel.D Sep 13 '16 at 07:47
  • 2
    @Daniel.D `void int fun1(){}` is not legal c++, please take a look at [How do I write a good answer?](http://stackoverflow.com/help/how-to-answer) – George Sep 13 '16 at 08:16