difference between break and return

  • Thread starter Thread starter tony collier
  • Start date Start date
T

tony collier

To break out of a loop i have seen some people use RETURN instead of BREAK

I have only seen RETURN used in functions. Does anyone know why RETURN is
used instead of BREAK to kill loops?
 
True purists will say that a function should only have a single entry (at
the top) and exit (at the bottom) point.

Really, it gets down to whether or not you want to continue executing your
code after a certain loop condition has happened. Those that use returns
within a loop (and I am guilty of the occasional usage myself) simply want a
quick way to exit the function without writing additional logic to support
the "single exit" philosophy.

Remember, they do have different purposes as BREAK will only exit the loop
that you are in but execution of the function continues.
 
thankyou. don't chastise yourself too harshly - the example that got me
thinking was microsoft coded.
 
G'Day Tony,

The major difference between break and return is that with return you exit
the method whereas with break not necessarily. I suggest the use of break in
loops rather than return.
 
"Eki Y. Baskoro" said:
The major difference between break and return is that with return you exit
the method whereas with break not necessarily. I suggest the use of break in
loops rather than return.

You could consider "break" to be like that most hated of programming
language commands, "goto". It causes your program to immediately go to the
right-hand side of the closing brace of the closest loop.

F'rinstance:

int a[100];
for (i=0;i<10;i++)
{
for (j=0;j<10;j++)
{
a[i*10+j]=1;
if (i==j) break;
a[i*10+j]=1;
} // <-- The 'break' jumps to just after this brace,
// and before any statements that follow it.
} // <-- The 'break' does not jump to this brace,
// because there's a closer brace that terminates a loop.

Note that this rather clumsily creates something like the lower half of an
identity matrix in the array a. If we'd used a "return", then we would only
have set _one_ element - a[0] - to 1, and then exit the function. To create
the whole identity matrix, we'd use "continue" instead of "break" -
"continue" jumps to the _left_ hand side of the nearest loop-ending brace.

Essentially, "continue" means "stop processing this leg of this loop, and go
round again." "break" means "stop processing this loop". "return" means
"quit the subroutine / function / method that we're in" - it'll skip out of
any number of enclosing loops.

Alun.
~~~~

[Please don't email posters, if a Usenet response is appropriate.]
 
Back
Top