I was under the impression that any function in C would support only one return statement until I came across a few notes where there was a mention of multiple return statements. How do these multiple return statements work?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The first
returnstatement that is executed will terminate the function and its value will be used.However, there can obviously be multiple execution paths – and they can return different values. Actually in a non-void function every possible execution path has to return something. The easiest way to achieve this is obviously having a
returnstatement at the very end of the function.There are some arguments for having just a single return statement in your code; consider reading the article if any of them apply to you. A good example is code that always needs to do some clean-up. In this case you will only want to return after this has been done – so you’ll set a variable for the return value and use
gototo jump to the cleanup-and-return section at the end of the function if you need to return early.