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?
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?
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.