-3

I learning c++. And I have a question. When do I have to use 'return'? And what does 'return' do in the function? And if I didn't use 'return' in function what will happen?

What is different when I use 'return' in function or not?

  • 3
    The `return` statement causes the current function to immediately exit. If you have declared the function to not return a value (i.e. its return type is `void`) then you can let the function run to its natural end or leave the function prematurely using `return;`. If you declared the function to return a value, you must return a value, otherwise the caller which uses that value won't have a value. That leads to *undefined behavior*. This should all be explained in [good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282). – Some programmer dude Feb 04 '22 at 11:50
  • It's like when you go away somewhere and then you return to where you came from, except if you weren't supposed to bring something back, you will return automatically when you're done with whatever you were doing. If you *were* supposed to bring something back and don't, there is no telling what will happen. – molbdnilo Feb 04 '22 at 11:57
  • What does your book say about `return`? Post a quotation and explain what you don't understand in it. – n. m. could be an AI Feb 04 '22 at 12:10
  • In my book say **return** return the values. I understand that. But I don't when do I have to use **return**. – SoSok the Programmer Feb 04 '22 at 12:19

1 Answers1

3

But I don't [know] when do I have to use return?

You need to use return when you need to leave the function before the natural end (before the functions last closing }) of it. Or at the natural end if you're supposed to return with a value.

For example:

  • Function without a return:

    void print_hello()
    {
        std::cout << "Hello\n";
    }
    

    The function is declared to return void, i.e. it returns nothing. So no return statement is needed.

  • Function that returns before the "natural" end of the function:

    void print_if_condition(bool condition)
    {
        if (!condition)
        {
            // If the condition is false, return from the function
            return;
        }
    
        std::cout << "Hello\n";
    }
    

    If the condition is false then the function will return immediately, and the output will not be written.

  • Returning with a value:

    int add_two_integers(int a, int b)
    {
        // Returns the result of a + b
        return a + b;
    }
    

    A function declared to return a value should always use return (with an expression which is the value that will be returned). This return statement is needed even if the function runs to its "natural" end.

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