-
August 4th, 2011, 01:27 PM
#1
Return from within a loop that's inside a function?
I have a function that contains a do loop. Can I return from inside the loop? Like this:
Code:
int myfunction(char *str, ...){
...
do {...
n = read(...);
if (n<0){ // error reading from serial port
if (errno==EBADF || errno==EIO){
return (-1); // exit from function while still inside the do loop, is this OK?
}
}
if (n > 0) { // process read data
...
}
} while ( ... );
...
return ntot; // normal exit from function
}
Thanks!
-
August 4th, 2011, 01:36 PM
#2
Re: Return from within a loop that's inside a function?
Yes. You could have tried and found out for yourself.
-
August 4th, 2011, 01:37 PM
#3
Re: Return from within a loop that's inside a function?
It's certainly possible. Some coding standards recommend using a single-point-of-return, however.
The main benefit of single-point-of-return is that if you used any resources in the function (opened files, malloc'd memory, locked mutexes, etc) you can organize your code to make absolutely certain that all of those things are released prior to the function return without needing to duplicate the release code in several places.
On the other hand, if you just use RAII techniques to manage those resources, then they are released automatically on function return anyway, no matter where it is done.
So in summary: yes, you can do it. Just be cautious to clean up after yourself properly if you do.
-
August 4th, 2011, 02:03 PM
#4
Re: Return from within a loop that's inside a function?
 Originally Posted by Lindley
It's certainly possible. Some coding standards recommend using a single-point-of-return, however.
The main benefit of single-point-of-return is that if you used any resources in the function (opened files, malloc'd memory, locked mutexes, etc) you can organize your code to make absolutely certain that all of those things are released prior to the function return without needing to duplicate the release code in several places.
On the other hand, if you just use RAII techniques to manage those resources, then they are released automatically on function return anyway, no matter where it is done.
So in summary: yes, you can do it. Just be cautious to clean up after yourself properly if you do.
That was the concern. Thank you!
-
August 4th, 2011, 04:50 PM
#5
Re: Return from within a loop that's inside a function?
 Originally Posted by acppdummy
That was the concern.
Just because you can do something doesn't mean it's good practice, not even if the code works.
The consensus view is that it's okay to use multipoint returns with care on occasion. It's definately not good practice to have zillions of returns all over the place.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|