Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A Return inside and outside an If Statement

This is probably a fairly easy question to answer, but it has been bugging me some time.

If there is a return statement inside an if statement, inside a method (in the Java language), but I add another at the end as a catch-all and to avoid the error, are both return values going to be fired one after the other if the if statement is true?

An example:

public int getNumber() {
 if( 5 > number) {
 return 5;
 }
 return 0;
 }

Result: Method returns 5, and then via stacks logic, returns 0 shortly thereafter.

Or, do I need to use an outside variable like so:

int num = 1;
public int getNumber() {
 if( 5 > number) {
 num = 5;
 }
 return num;
 }

Result: Method changes variable num to 5, then num is returned for use. I suppose in this case, the return statement wouldn't necessarily be required depending on the variable's usage.

Thanks in advance.

like image 284
A13X Avatar asked Aug 16 '13 22:08

A13X


People also ask

Can you have a return in an if statement?

No, both values aren't going to be returned. A return statement stops the execution of the method right there, and returns its value. In fact, if there is code after a return that the compiler knows it won't reach because of the return , it will complain.

Why we use return in if statement?

A return statement ends the execution of a function, and returns control to the calling function. Execution resumes in the calling function at the point immediately following the call. A return statement can return a value to the calling function.

What does return do in if else statement?

Every return statement is inside an if statement. While it may be logically impossible as written, the compiler needs a return for when none of the if evaluate true. This solution fixes the compiler problem and improves readability slightly, in my opinion.

Can we write return statement in if block?

Is it possible to write return statement in if block? It is possible, but you haven't covered all the possible cases to which the program flow may go.


2 Answers

No, both values aren't going to be returned. A return statement stops the execution of the method right there, and returns its value. In fact, if there is code after a return that the compiler knows it won't reach because of the return, it will complain.

You don't need to use a variable outside the if to return it at the end. However, if your method is long and complex, this technique can help readability and clarity because only one return statement is used.

like image 171
rgettman Avatar answered Oct 30 '22 06:10

rgettman


Only the first return statement hit is used. The method then terminates.

There are some code conventions that frown on multiple return statements because they might be hard to read, but I'm not one of them. :)

like image 37
Xabster Avatar answered Oct 30 '22 05:10

Xabster