Can a function that dosnt return values, have a return statement.? What is it's effect?
Printable View
Can a function that dosnt return values, have a return statement.? What is it's effect?
Some compilers will let you have an empty return statement. Those statements end the function but do not return anything. Not all compilers will accept those statements so do not use them.
All compilers should accept an empty return statement with void functions:
Code:void function() {
return; // this is always okay
}
the function execution stops and control returns to the calling functionQuote:
What is it's effect?
Code:void print_string(char* string)
{
if(string == NULL)
return; /* we do not want continue if the null-pointer was put as a parameter */
/* do something useful with the string */
}
Which horribly broken compilers will not allow early returns from void functions?Quote:
Originally Posted by Desolation
Sometimes you want to return from a void function earlier than the closing brace, in which case the compiler had better support it.
MSVC++ 7.3. I can't do that.Quote:
Originally Posted by CornedBee
What is 7.3? Do you mean 2003 (7.1)?
I think you might be confused though. You can do it just fine in VC++ 6.0 and higher (and probably in previous versions as well). Also, we are talking about C++ here, not C.Code:#include <iostream>
void output_if_positive(int value)
{
if (value <= 0)
return;
std::cout << value << '\n';
}
int main()
{
output_if_positive(-2);
output_if_positive(5);
}
Maybe I confused the IDEs, but I am 100% positive that I have tried an empty return statement in a compiler and have got an error because of it.
I'm 100% positive the error was something else and you confused it with an empty return in a void function. Maybe an empty return in a non-void function, or a non-empty return in a void function, but an empty return in a void function has always been legal C++.