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, works locally and does not alter any value or work with any value outside its scope (high cohesion). It also returns some value. A subroutine works directly with the values of the caller or code segment which invoked it and does not return values (low cohesion), i.e. branching some code to some other code in order to do some processing and come back.
Is this true? Or is there no difference, just two terms to denote one?
A function must return a single value, and can be invoked from within expressions, like a write statement, inside an if declaration if (function) then , etc. A subroutine does not return a value, but can return many values via its arguments and can only be used as a stand-alone command (using the keyword call ).
A sub performs a task but does not return a value. A function returns a value of the tasks performed. Subs can be recalled from anywhere in the program and in multiple types. Functions are called by a variable.
In Fortran, functions are invoked or referenced; subroutines are called. Normally, the invoking or calling program passes on to the subprogram a set of arguments. The subprogram uses these arguments to compute the results and to pass them back and return control to the invoking or calling program.
I disagree. If you pass a parameter by reference to a function, you would be able to modify that value outside the scope of the function. Furthermore, functions do not have to return a value. Consider void some_func()
in C. So the premises in the OP are invalid.
In my mind, the difference between function and subroutine is semantic. That is to say some languages use different terminology.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With