This question already has answers here:
What's the difference between an argument and a parameter?
(38 answers)
Closed 10 years ago.
Is there a difference between a "parameter" and an "argument", or are they simply synonyms?
Argument is often used in the sense of actual argument vs. formal parameter.
The formal parameter is what is given in the function declaration/definition/prototype, while the actual argument is what is passed when calling the function — an instance of a formal parameter, if you will.
That being said, they are often used interchangeably, their exact use depending on different programming languages and their communities. For example, I have also heard actual parameter etc.
So here, x and y would be formal parameters:
int foo(int x, int y) {
...
}
Whereas here, in the function call, 5 and z are the actual arguments:
foo(5, z);
Generally, the parameters are what are used inside the function and the arguments are the values passed when the function is called. (Unless you take the opposite view — Wikipedia mentions alternative conventions when discussing parameters and arguments).
double sqrt(double x)
{
...
return x;
}
void other(void)
{
double two = sqrt(2.0);
}
Under my thesis, x is the parameter to sqrt() and 2.0 is the argument.
The terms are often used at least somewhat interchangeably.
They are often used interchangeably in text, but in most standards the distinction is that an argument is an expression passed to a function, where a parameter is a reference declared in a function declaration.
Arguments and parameters are different
in that parameters are used to different values in the program and
The arguments are passed the same value
in the program so they are used in c++.
But no difference in c. It is the same for arguments and parameters in c.
Related
Documentation:
Argument-type declarations normally have no impact on performance:
regardless of what argument types (if any) are declared, Julia
compiles a specialized version of the function for the actual argument
types passed by the caller. For example, calling fib(1) will trigger
the compilation of specialized version of fib optimized specifically
for Int arguments, which is then re-used if fib(7) or fib(15) are
called.
The provided example:
fib(n::Integer) = n ≤ 2 ? one(n) : fib(n-1) + fib(n-2)
but then in the Performance Tips:
# This will not specialize:
function f_type(t) # or t::Type
x = ones(t, 10)
return sum(map(sin, x))
end
From my understanding of the performance tips, with or without type annotations fib(b::Integer) or fib(b) shouldn't specialize specifically for Int arguments.
It seems with or without the type annotation no specialization will happen, but why does the manual seem to indicate that it will specialize?
The example in the Performance Tips page is about the specific case where you pass the type itself as the argument to the function. As the beginning of that section says:
Julia avoids automatically specializing on argument type parameters in three specific cases: Type, Function, and Vararg
f_type in that example is a function that accepts a Type t. A call to that function will look like, for eg., f_type(Int). The section says that type specialization isn't done based on the Int type in this case, where the Int is passed as a value of the parameter itself (and then passed through to another function). (Specifically, the Type isn't specialized into a specific parametrized type like Type{Int}, as it normally would be if the argument wasn't one of the above mentioned three cases.)
This doesn't apply to the fib method (or most methods we normally define). fib accepts a value whose type is (a subtype of) Integer, not the type itself. In such cases, a call like fib(1) or fib(UInt8(2)) does create type-specialized compiled versions of the function.
In layman words, Julia will always specialize on function arguments either with or without annotation, except in three cases. One of them is when the arguments are passed to another function, since specializing twice will slow compilation down, and it will finally be specialized at the inner function call, so no performance hit occurs.
So, fib(n:Int) is equivalent to fib(n) and both will use a specialized compiled version of the function for the Int64 type unless n is already of a different type than Int64, it will specialize for that type.
I was under the impression that the main differences between subroutines and functions in Fortran was that functions returned values, while subroutines change some or all of the values passed as arguments. But then I learned that you could modify variables passed in to functions as arguments too. I'm confused, and can't find a good reference for the differences between them.
So, what are the differences between the two constructs, and when and why should one be preferred over the other?
Whether to use one or another is more or less a matter of programming style. You are allowed to write the arguments of both functions and subroutines as intent(in), intent(inout) or intent(out).
My personal style is however to only use the intent(in) arguments for functions, which is also a requirement for pure functions. An exception to this rule can be made when en error code intent(out) argument is necessary.
There is a subtle trap hidden in functions which return different results for the same input argument value. Consider a hypothetical function returning a random number
real function rnd()
end function
calling it once
x = rnd()
is completely OK. Calling it multiple times in a single expression
x = (rnd() + rnd()) / 2
can result in the function being called only once. Fortran language rules allow such behaviour. Therefore, the standard Fortran procedure for getting random numbers random_number() is a subroutine (and because all intrinsic functions are pure).
Where ever you cannot use a function, use a subroutine.
Any function can by converted to a subroutine by moving the result variable to a dummy argument with intent(out). The opposite process may be more problematic.
How is this possible, what is going on there?
Is there a name for this?
What other languages have this same behavior?
Any without the strong typing system?
This behaviour is really simple and intuitive if you look at the types. To avoid the complications of infix operators like +, I'm going to use the function plus instead. I'm also going to specialise plus to work only on Int, to reduce the typeclass line noise.
Say we have a function plus, of type Int -> Int -> Int. One way to read that is "a function of two Ints that returns an Int". But that notation is a little clumsy for that reading, isn't it? The return type isn't singled out specially anywhere. Why would we write function type signatures this way? Because the -> is right associative, an equivalent type would be Int -> (Int -> Int). This looks much more like it's saying "a function from an Int to (a function from an Int to an Int)". But those two types are in fact exactly the same, and the latter interpretation is the key to understanding how this behaviour works.
Haskell views all functions as being from a single argument to a single result. There may be computations you have in mind where the result of the computation depends on two or more inputs (such as plus). Haskell says that the function plus is a function that takes a single input, and produces an output which is another function. This second function takes a single input and produces an output which is a number. Because the second function was computed by first (and will be different for different inputs to the first function), the "final" output can depend on both the inputs, so we can implement computations with multiple inputs with these functions that take only single inputs.
I promised this would be really easy to understand if you looked at the types. Here's some example expressions with their types explicitly annotated:
plus :: Int -> Int -> Int
plus 2 :: Int -> Int
plus 2 3 :: Int
If something is a function and you apply it to an argument, to get the type of the result of that application all you need to do is remove everything up to the first arrow from the function's type. If that leaves a type that has more arrows, then you still have a function! As you add arguments the right of an expression, you remove parameter types from the left of its type. The type makes it immediately clear what the type of all the intermediate results are, and why plus 2 is a function which can be further applied (its type has an arrow) and plus 2 3 is not (its type doesn't have an arrow).
"Currying" is the process of turning a function of two arguments into a function of one argument that returns a function of another argument that returns whatever the original function returned. It's also used to refer to the property of languages like Haskell that automatically have all functions work this way; people will say that Haskell "is a curried language" or "has currying", or "has curried functions".
Note that this works particularly elegantly because Haskell's syntax for function application is simple token adjacency. You are free to read plus 2 3 as the application of plus to 2 arguments, or the application of plus to 2 and then the application of the result to 3; you can mentally model it whichever way most fits what you're doing at the time.
In languages with C-like function application by parenthesised argument list, this breaks down a bit. plus(2, 3) is very different from plus(2)(3), and in languages with this syntax the two versions of plus involved would probably have different types. So languages with that kind of syntax tend not to have all functions be curried all the time, or even to have automatic currying of any function you like. But such languages have historically also tended not to have functions as first class values, which makes the lack of currying a moot point.
In Haskell, all functions take exactly 1 input, and produce exactly 1 output. Sometimes, the input to or output of a function can be another function. The input to or output of a function can also be a tuple. You can simulate a function with multiple inputs in one of two ways:
Use a tuple as input
(in1, in2) -> out
Use a function as output*
in1 -> (in2 -> out)
Likewise, you can simulate a function with multiple outputs in one of two ways:
Use a tuple as output*
in -> (out1, out2)
Use a function as a "second input" (a la function-as-output)
in -> ((out1 -> (out2 -> a)) -> a)
*this way is typically favored by Haskellers
The (+) function simulates taking 2 inputs in the typical Haskell way of producing a function as output. (Specializing to Int for ease of communication:)
(+) :: Int -> (Int -> Int)
For the sake of convenience, -> is right-associative, so the type signature for (+) can also be written
(+) :: Int -> Int -> Int
(+) is a function that takes in a number, and produces another function from number to number.
(+) 5 is the result of applying (+) to the argument 5, therefore, it is a function from number to number.
(5 +) is another way to write (+) 5
2 + 3 is another way of writing (+) 2 3. Function application is left-associative, so this is another way of writing (((+) 2) 3). In other words: Apply the function (+) to the input 2. The result will be a function. Take that function, and apply it to the input 3. The result of that is a number.
Therefore, (+) is a function, (5 +) is a function, and (+) 2 3 is a number.
In Haskell, you can take a function of two arguments, apply it to one argument, and get a function of one argument. In fact, strictly speaking, + isn't a function of two arguments, it's a function of one argument that returns a function of one argument.
In layman's terms, the + is the actual function and it is waiting to receive a certain number of parameters (in this case 2 or more) until it returns. If you don't give it two or more parameters, then it will remain a function waiting for another parameter.
It's called Currying
Lots of functional languages (Scala,Scheme, etc.)
Most functional languages are strongly typed, but this is good in the end because it reduces errors, which works well in enterprise or critical systems.
As a side note, the language Haskell is named after Haskell Curry, who re-discovered the phenomenon of Functional Currying while working on combinatory logic.
Languages like Haskell or OCaml have a syntax that lends itself particularily to currying, but you can do it in other languages with dynamic typing, like currying in Scheme.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
What is the difference between a ‘function’ and a ‘procedure’?
I searched online for an answer to this question, and the answer I got was that a function can return a value, modify a value, etc., but a subroutine cannot. But I am not satisfied with this explanation and it seems to me that the difference ought to be more than just a matter of terminology.
So I am looking for a more conceptual answer to the question.
A function mirrors the mathematical definition of a function, which is a mapping from 1 or more inputs to a value.1
A subroutine is a general-purpose term for any chunk of code that has a definite entry point and exit point.
However, the precise meaning of these terms will vary from context to context.
1. Obviously, this is not the formal mathematical definition of a function.
A generic definition of function in programming languages is a piece of code that accepts zero or more input values and returns zero or one output value.
The most common definition of subroutine is a function that does not return anything and normally does not accept anything. It is only a piece of code with a name.
Actually in most languages functions do not differ in the way you declare them. So a subroutine may be called a function, but a function not necessarily may be called a subroutine.
Also there is people that consider functions and subroutines the same thing with a different name.
Subroutine - Wikipedia
It's worth noting as an addendum to #Oli's answer that in the mathematical sense a function must be "well-defined", which is to say its output is uniquely determined by its inputs, while this often isn't the case in programming languages.
Those that do make this guarantee (and also that their functions not cause side-effects) are called pure functional languages, an example of which being Haskell. They have the advantage (among others) of their functions being provably correct in their behaviour, which is generally not possible if functions rely on external state and/or have side-effects.
A function must return some value and must not change a global variable or a variable declared outside of the function's body. Under this situation, a function can only mimic it's mathematical counter part (the thing which maps a mathematical object to another mathematical object)
A subroutine doesn't return anything and usually is impure as it has to change some global state or variable otherwise there is no point in calling it. There is no mathematical parallel for a subroutine.
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?
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.
A function returns a value whereas a subroutine does not. A function should not change the values of actual arguments whereas a subroutine could change them.
Thats my definition of them ;-)
If we talk in C, C++, Java and other related high level language:
a. A subroutine is a logical construct used in writing Algorithms (or flowcharts) to designate processing functionality in one place. The subroutine provides some output based on input where the processing may remain unchanged.
b. A function is a realization of the Subroutine concept in the programming language
Both function and subroutine return a value but while the function can not change the value of the arguments coming IN on its way OUT, a subroutine can. Also, you need to define a variable name for outgoing value, where as for function you only need to define the ingoing variables. For e.g., a function:
double multi(double x, double y)
{
double result;
result = x*y;
return(result)
}
will have only input arguments and won't need the output variable for the returning value. On the other hand same operation done through a subroutine will look like this:
double mult(double x, double y, double result)
{
result = x*y;
x=20;
y = 2;
return()
}
This will do the same as the function did, that is return the product of x and y but in this case you (1) you need to define result as a variable and (2) you can change the values of x and y on its way back.
One of the differences could be from the origin where the terminology comes from.
Subroutine is more of a computer architecture/organization terminology which means a reusable group of instructions which performs one task. It is is stored in memory once, but used as often as necessary.
Function got its origin from mathematical function where the basic idea is mapping a set of inputs to a set of permissible outputs with the property that each input is related to exactly one output.
In terms of Visual Basic a subroutine is a set of instructions that carries out a well defined task. The instructions are placed within Sub and End Sub statements.
Functions are similar to subroutines, except that the functions return a value. Subroutines perform a task but do not report anything to the calling program. A function commonly carries out some calculations and reports the result to the caller.
Based on Wikipedia subroutine definition:
In computer programming, a subroutine is a sequence of program
instructions that perform a specific task, packaged as a unit. This
unit can then be used in programs wherever that particular task should
be performed.
Subroutines may be defined within programs, or separately in libraries
that can be used by many programs. In different programming languages,
a subroutine may be called a procedure, a function, a routine, a
method, or a subprogram. The generic term callable unit is sometimes
used.
In Python, there is no distinction between subroutines and functions.
In VB/VB.NET function can return some result/data, and subroutine/sub can't.
In C# both subroutine and function referred to a method.
Sometimes in OOP the function that belongs to the class is called a method.
There is no more need to distinguish between function, subroutine and procedure because of hight level languages abstract that difference, so in the end, there is very little semantic difference between those two.
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.
From the view of the user, there is no difference between a programming function and a subroutine but in theory, there definitely is!
The concept itself is different between a subroutine and a function. Formally, the OP's definition is correct. Subroutines don't take arguments or give return values by formal semantics. That's just an interpretion with conventions. And variables in subroutines are accessible in other subroutines of the same file although this can be achieved as well in C with some difficulties.
Summary:
Subroutines work only based on side-effects, in the view of the programming language you are programming with. The concept itself has no explicit arguments or return values. You have to use side effects to simulate them.
Functions are mappings of input to output value(s) in the original sense, some kind of general substitution operation. In the adopted sense of the programming world, functions are an abstraction of subroutines with information about return value and arguments, inspired by mathematical functions. The additional formal abstraction differentiates a function from a subroutine in programming context.
Details:
The subroutine originally is simply a repeatable snippet of code which you can call in between other code. It originates in Assembly or Machine language programming and designates the instruction sequence itself. In the light of this meaning, Perl also uses the term subroutine for its callable code snippets.
Subroutines are concrete objects.
This is what I understood: the concept of a (pure) function is a mathematical concept which is a special case of mathematical relations with an own formal notation. You have an input or argument and it is defined what value is represented by the function with the given argument. The original function concept is entirely unrelated to instructions or calculations. Mathematical operations (or instructions in the programming world) only are a popular formal representation (description) of the actual mapping. The original function term itself is not defined as code. Calculations do not constitute the function, so that functions actually don't have any computational overhead because they are direct mappings. Function complexity considerations only arrived as there is an overhead to find the mapping.
Functions are abstract objects.
Now, since the whole PC-stuff is running on small machine instructions, the easiest way to model (or instantiate) mathematics is with a sequence of instructions itself. Computer Science has been founded by mathematicians (noteworthy: Alan Turing) and the first programming concepts are based on it so there is a need to bring mathematics into the machine. That's how I imagine the reason why "function" is the name of something which is implemented as subroutine and why the term "pure" function was coined to differentiate the original function concept from the overly broad term-use in programming languages.
Note: in Assembly Language Programming, it is typically said, that a subroutine has been passed arguments and gives a return value. This is an interpretation on top of the concrete formal semantics. Calling conventions specify the location where values, to be considered as arguments and return values, should be written to before calling a subroutine or returning. The call itself takes only a subroutine address, and has no formal arguments or return values.
PS: functions in programming languages don't necessarily need to be a subroutine (even though programming language terminology developed this way). Functions in functional programming languages can be constant variables, arrays or hash tables. Isn't every datastructure in ECMAScript a function?
The difference is isolation. A subroutine is just a piece of the program that begins with a label and ends with a go to. A function is outside the namespace of the rest of the program. It is like a separate program that can have the same variable names as used in the calling program, and whatever it does to them does not affect the state of those variables with the same name in the calling program.
From a coding perspective, the isolation means that you don’t have to use the variable names that are local to the function.
Sub double:
a = a + a
Return
fnDouble(whatever):
whatever = whatever + whatever
Return whatever
The subroutine works only on a. If you want to double b you have to set a = b before calling the subroutine. Then you may need to set a to null or zero after. Then when you want to double c you have to again set a to equal c.
Also the sub might have in it some other variable, z, that is changed when the sub is jumped to, which is a bit dangerous.
The essential is isolation of names to the function (unless declared global in the function.)
I am writing this answer from a VBA for excel perspective. If you are writing a function then you can use it as an expression i. e. you can call it from any cell in excel.
eg: normal vlookup function in excel cannot look up values > 256 characters. So I used this function:
Function MyVlookup(Lval As Range, c As Range, oset As Long) As Variant
Dim cl As Range
For Each cl In c.Columns(1).Cells
If UCase(Lval) = UCase(cl) Then
MyVlookup = cl.Offset(, oset - 1)
Exit Function
End If
Next
End Function
This is not my code. Got it from another internet post. It works fine.
But the real advantage is I can now call it from any cell in excel. If wrote a subroutine I couldn't do that.
Every subroutine performs some specific task. For some subroutines, that task is to compute or retrieve some data value. Subroutines of this type are called functions. We say that a function returns a value. Generally, the returned value is meant to be used somehow in the program that calls the function.