How does a return
statement differ from break
statement?.
If I have to exit an if condition, which one should I prefer, return
or break
?
These are jumping statements. break is used to exit from a loop or a switch-case. continue is used to move the control to the next iteration of the loop. return is used to return a value from a function.
break is used to end a loop prematurely while return is the keyword used to pass back a return value to the caller of the function. If it is used without an argument it simply ends the function and returns to where the code was executing previously.
In nested loops, break exits only from the loop in which it occurs. Control passes to the statement that follows the end of that loop. It retains the control in the outer block of the loop. return forces MATLAB to return control to the invoking function before it reaches the end of the function.
The primary difference between break and continue statement in C is that the break statement leads to an immediate exit of the innermost switch or enclosing loop. On the other hand, the continue statement begins the next iteration of the while, enclosing for, or do loop.
break
is used to exit (escape) the for
-loop, while
-loop, switch
-statement that you are currently executing.
return
will exit the entire method you are currently executing (and possibly return a value to the caller, optional).
So to answer your question (as others have noted in comments and answers) you cannot use either break
nor return
to escape an if-else
-statement per se. They are used to escape other scopes.
Consider the following example. The value of x
inside the while
-loop will determine if the code below the loop will be executed or not:
void f()
{
int x = -1;
while(true)
{
if(x == 0)
break; // escape while() and jump to execute code after the the loop
else if(x == 1)
return; // will end the function f() immediately,
// no further code inside this method will be executed.
do stuff and eventually set variable x to either 0 or 1
...
}
code that will be executed on break (but not with return).
....
}
break
is used when you want to exit from the loop, while return
is used to go back to the step where it was called or to stop further execution.
No offence, but none of the other answers (so far) has it quite right.
break
is used to immediately terminate a for
loop, a while
loop or a switch
statement. You can not break
from an if
block.
return
is used the terminate a method (and possibly return a value).
A return
within any loop or block will of course also immediately terminate that loop/block.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With