Breaking out of function in c++
how do you leave a function in the middle? i have a condition for leaving the function, but i dont know how to actually leave.
ex:
voi开发者_C百科d a(int &num){
if (num > 100){
// leave function
}
num += a(num + 1);
}
i want to end the recursion, and i have to keep the function a void
void a(int &num){
if (num > 100){
return;
}
num += a(num + 1);
}
As pointed in the comments by Martin York, I jumped on the answer without considering every aspect of the question, and for that I apologize. What you want is probably :
int a(int num)
{
if (num > 100)
return num;
return num + a(num + 1);
}
Nothing stops you from putting a return
in the middle of the function, although some people may argue that it's bad style.
The main motivation for that idea is that if you have multiple return points in your function it's more difficult to maintain the cleanup code, that will have to be spread at each return; however, using the modern RAII pattern (that is required if you want your code to be exception-safe) you should have no problems in having multiple exit points: the cleanup code (that is contained in the destructors of the resource-holding objects) will be called anyway.
You can use return.
But you need a value:
int a(int num)
{
if (num > 100)
{
return num;
}
num += a(num + 1);
return num;
}
void a(int num)
{
if (num > 100)
{
}
else
{
num += a(num + 1);
}
}
Since the function returns a value, a return
statement with a value needs to be given:
int a(int num){
if (num > 100){
return 100;// leave function
}
num += a(num + 1);
return num;
}
For functions not returning a value, use return;
.
You could use something like this. Notice that no return value is needed since it is a void function. and the void is very empty.
void a(int &num){
if (num > 100){
return;
}
num += a(num + 1);
}
But I rather see the code sample above like this.
void a(int &num){
if(!(num >100)){
num += a(num + 1);
}
}
int a(int num){
if (num > 100){
return num; // or return 100;
}
num += a(num + 1);
return num;
}
By the way if your are using references (int &num) you can not pass num + 1 as parameter.
Some people don't like to have more than one return statement in a function:
void a(..)
{
if (...)
goto end;
....
end:
return;
}
I, on the other hand, think they're stupid.
Yes, I've seen it.
精彩评论