Why is "return" required in "if" when replacing the "else"?

Viewed 49

I was creating a simple sum function which receives an input n and adds all the numbers from 1 to n. I have managed to do it by creating a simple function which looks like this and calling it with add being 1 each time:

fn summ (nr: u128, add: u128) -> u128{
    if add <= nr {
        add + summ(nr, add+1)
    } else {
        0
    }
}

The function works fine, however after playing around with it I ecountered some errors.

If I remove the else and leave the 0 outside the if statement like this,

fn summ (nr: u128, add: u128) -> u128{
    if add <= nr {
        add + summ(nr, add+1)
    }
    0
}

the program won't compile, saying it expected a () but found u128 on the add + summ(nr, add+1) line, which is fixed by adding a ; to the end.

However that obviously makes it return 0 all the time. The fix to this was preceding the add + summ(nr, add+1) line with return.

Why does adding return make the program compile and why does it not work without, and why did it work in the first case but not the second?

0 Answers
Related