Difference between Return and Break statements

Difference between Return and Break statements

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?

 

回答

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.

 

posted @ 2022-07-12 15:02  ChuckLu  阅读(25)  评论(0)    收藏  举报