What is the difference between a function and a subroutine?

前端 未结 11 1560
攒了一身酷
攒了一身酷 2021-01-30 06:32

What is the difference between a function and a subroutine? I was told that the difference between a function and a subroutine is as follows:

A function takes parameters

11条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 07:28

    Yes, they are different, similar to what you mentioned.

    A function has deterministic output and no side effects.
    A subroutine does not have these restrictions.

    A classic example of a function is int multiply(int a, int b)
    It is deterministic as multiply(2, 3) will always give you 6.
    It has no side effects because it does not modify any values outside its scope, including the values of a and b.

    An example of a subroutine is void consume(Food sandwich)
    It has no output so it is not a function.
    It has side effects as calling this code will consume the sandwich and you can't call any operations on the same sandwich anymore.

    You can think of a function as f(x) = y, or for the case of multiply, f(a, b) = c. Yes, this is programming and not math. But math models and begs to be used. So we use math in cs. If you are interested to know why the distinction between function and subroutine, you should check out functional programming. It works like magic.

提交回复
热议问题