You don’t *need* one, and not all languages have one. But they are pretty useful.
Programs are usually divided into functions, mini-programs that perform a specific task. They can be things like GenerateRandomNumber(), InvertMatrix(), or ComputePrice(). They do their thing and come up with a value…return(341) is one way they communicate that value back to whatever requested the function.
Also, a return statement can be used to exit a function early when there is a special case. ComputePrice() might have a statement early on like “if ShoppingCart.size() == 0, return 0” so it doesn’t do unnecessary work when a shopping cart is empty.
Latest Answers