+ 2

Should keyword return be at the end of method always?

30th Aug 2019, 7:44 PM
Moho
Moho - avatar
4 Respostas
+ 4
if a method has a return type there must be a return at the end of the method, but it is possible to put return statments earlier in the method, but keep in mind once a return statment is hit the rest of the method does not get executed.
30th Aug 2019, 9:04 PM
Anton Böhler
Anton Böhler - avatar
+ 3
Most compilers also throw a warning (or even error) for anything that comes after return, something along the lines of "unreachable code"
30th Aug 2019, 9:47 PM
HNNX 🐿
HNNX 🐿 - avatar
+ 2
No, if it's a method returning void the return keyword is not necessary at the end of the method.
30th Aug 2019, 7:56 PM
Miquel Andreu Fuster Sancho
Miquel Andreu Fuster Sancho - avatar
0
+ if return is only inside if() block (without else) you get error: missing return statement int method(){ if(true) { return 100; } // return 0; }
30th Aug 2019, 11:12 PM
zemiak