-2

I tried to find my question but i didn't so i will open this subject. What the return 0 does in a function? Like:

double moneyBonus(double money)
{
    if (money >= 0 && money <= 1000)
    {
        return money * (3.0/100.0);
    }
    return 0.0; // same results if i remove it
}

Thanks in advance! EDIT: it says that question is duplicate, i tried to understand the other post but i didn't understand it so i made mine. I don't know how this duplicate think works!

stathis21098
  • 31
  • 13

4 Answers4

1

That's because you're always going into your if statement and using return money * (3.0/100.0);. Try calling moneyBonus with money less than 0 or greater than 1000, then you'll hit the return 0.0;.

Paul Evans
  • 27,315
  • 3
  • 37
  • 54
  • Can you please explain to me how it works? From the time it works with out it i cant understand and im comfused! – stathis21098 Oct 09 '15 at 21:05
  • You have an `if (money >= 0 && money <= 1000)` at the very beginning, if that's `true` you use the `return money * (3.0/100.0);` and *leave the function*, if `money >= 0 && money <= 1000` isn't `true` then you progress to the next statement (i.e. `return 0.0;`) and leave the function that way. Since you never execute the later, the `if` is *always* `true`. Make it false by calling `moneyBonus(2000)` and you'll get `0.0` as your `return` value. – Paul Evans Oct 09 '15 at 21:10
1

If the money variable is ever less than 0, or greater than 1000, (e.g fails the if) then your function will return the 0.0 that is outside the loop.

Without that return the function would not be able to return anything when the if statement failed.

bibzuda7
  • 64
  • 3
  • 10
1

The "return 0.0" will be executed when the if condition in your function is not True. It is like an else to your if.

Try calling the function with an input <0 or >1000, and you will see the "return 0.0" execute.

  • You mean try >0 and < 1000 right? – stathis21098 Oct 09 '15 at 21:07
  • Input >0 and <1000 will satisfy the 'if' condition, leading to the execution of "return money * (3.0/100.0)" If you want to see the "return 0.0" run, which I think is what you want to understand, try input <0 or >1000. –  Oct 09 '15 at 21:11
0

// same results if i remove it

try to call it for out of the if range and it would be different.

another thing, be careful about not writing this return cause it may result in unstable behavior. furthermore, your code will not be compiled on many compilers

Humam Helfawi
  • 19,566
  • 15
  • 85
  • 160