I have a function that returns int value but in some circumstances I want to terminate the function and return nothing.
Just to show an example:
int numberFunc(int num){
if(num > 10){
return;
/* terminates the function for numbers more than 10 */
}
return num;
}
This works fine but I get a warning that says the function has a return type of int but it doesn’t finish with a return statement.
Will there be a problem if I use something like this and what can be a solution for that?
Thanks
Solution:
As julemand101 explained, We can return a null value. Also the code above returns a null value for numbers more than 10 so we have to take care of the possible null values later on.
What you properly want is to return null
to indicate that the method are not returning any value:
int numberFunc(int num){
if(num > 10){
return null;
/* terminates the function for numbers more than 10 */
}
return num;
}
But remember that the method which are using the result from numberFunc needs to be aware that the returned value can be null
.