Multiple Functions With the Same Name

Multiple functions with the same name

You are allowed to define two functions with the same name if they have different Types, or if they can be distinguished by their external parameter argument labels. The Type of a function is composed of the parameter Types in parentheses, followed by ->, followed by the return Type. Note that the argument labels are NOT a part of the function's Type. (But see UPDATE below.)

For example, the following functions both have the same name and are of Type (Int, Int) -> Int:

// This:
func add(a: Int, b: Int) -> Int {
return a + b
}

// Is the same Type as this:
func add(x: Int, y: Int) -> Int {
return x + y
}

This will produce a compile-time error - changing the labels from a:b: to x:y: does not distinguish the two functions. (But see UPDATE below.)

Using Mr. Web's functions as examples:

// Function A: This function has the Type (UITableView, Int) -> Int
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ... }

// Function B: This function has the Type (UITableView, NSIndexPath) -> UITableViewCell
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { ... }

// Function C: This made up function will produce a compile-time error because
// it has the same name and Type as Function A, (UITableView, Int) -> Int:
func tableView(arg1: UITableView, arg2: Int) -> Int { ... }

Function A and Function B above do not conflict because they are of different Types. Function A and Function C above do conflict because they have the same Type. Changing the parameter labels does not resolve the conflict if the Types remain the same. (See UPDATE below.)

override is a different concept altogether, and I think some of the other answers cover it, so I'll skip it.

UPDATE: Some of what I wrote above is incorrect. It is true that a function's parameter labels are not a part of it's Type definition, but they can be used to distinguish two functions that have the same Type, so long as the function has external labels that are different such that the compiler can tell which function you are trying to call when you invoke it. Example:

func add(a: Int, to b: Int) -> Int {    // called with add(1, to: 3)
println("This is in the first function defintion.")
return a + b
}

func add(a: Int, and b: Int) -> Int { // called with add(1, and: 3)
println("This is in the second function definition")
return a + b
}

let answer1 = add(1, to: 3) // prints "This is in the first function definition"
let answer2 = add(1, and: 3) // prints "This is in the second function definition"

So, the use of external labels in a function definition will allow functions with the same name and of the same type to compile. So, it appears that you can write multiple functions with the same name so long as the compiler can distinguish them by their types or by their external signature labels. I don't think internal labels matter. (But I hope someone will correct me if I'm wrong.)

Can we define two functions with same name but different parameters?

I am confused when we need to define another function we can give it a different name.

The is the one of the most basic feature of C++: function overloading. In C you can't have two functions with the same name, at all. In C++, it's entirely possible as long as the function function signature is different, ie two functions having the same name but different set of parameters.

https://en.wikipedia.org/wiki/Function_overloading

How can different functions have the same name?

In Swift, the argument names and types are part of the function name. So in your example, the functions are named differently because the arguments are different.

This is why you see the argument names included in the method names in the documentation, for example:

locationManager(_:didUpdateLocations:)
locationManager(_:didFailWithError:)
locationManager(_:didFinishDeferredUpdatesWithError:)

Also, even if the arguments are named the same, if their types are different, this is allowed. A simple example:

class Greeter {
func greet(arg: Int) -> String {
if (arg < 12) {
return "Good morning!"
} else if (arg < 18) {
return "Good afternoon!"
} else {
return "Good evening!"
}
}

func greet(arg: String) -> String {
return "Hello, \(arg)."
}
}

In this example, you could call Greeter().greet(4) or Greeter().greet("Aaron") and control would flow to the appropriate function.

Static and multiple functions with same name in different headers

bool do_something(int a); is a prototype. It tells the compiler that function do_something requires a parameter of type int and returns a value of type bool.

When you call this function, the compiler can now check that you pass a correct argument and assign the return value to a variable of the correct type.

As C does not have function overloading, you will understand that there can only be one definition of the function in any one compilation unit. A compilation unit is a .c source file with all .h files included.

So the above description has no influence on linking whatsoever. If the function is not called, the prototype is not needed; if there is a prototype, it will not require the function to exist. And if the function is called, it may exist in any of the source files or libraries that are linked into the executable.

The keyword static for a function definition indicates that the function will only be visible to other functions in the compilation unit (and so must exist in source in the compilation unit). Inlcuding the static keyword in a .h file makes no sense as it will tell each source file in which the .h file is included that the function, if used, exists in that source file.

This description does have influence on the linking process, in the sense that if the function is used, it must be present in the current source file.

In your case, you must decide which of the two protoypes is correct and fix the .h file accordingly - or declare a second, different function, that takes the other parameter e.g. do_something_else.

How can I use multiple functions with the same name in other C files if they have the same name and I can't modify the other files?

You can use the preprocessor to change the function name for each file at compile-time, e.g.

$ gcc -Wall -Dfoo=foo_1 -c bar1.c
$ gcc -Wall -Dfoo=foo_2 -c bar2.c
$ gcc -Wall -Dfoo=foo_3 -c bar3.c
$ gcc -Wall main.c bar1.o bar2.o bar3.o

This way you can call functions foo_1(), foo_2(), foo_3() from main().

C#: Multiple functions with the same name and different signature, but the compiler calls the wrong one. How to fix it?

call it by using named parameter

        Database d = new Database();

//ExecuteScalar
d.Insert(table: "demoTabele", returnedColumn: "returnedColumn",values: new string[]{"rest arguments1", "rest arguments2"});

//ExecuteNonQuery
d.Insert(table: "demoTabele", values: new string[] { "rest arguments1", "rest arguments2" });

Two Javascript functions with same name are calling the same parameterised function always

JavaScript doesn't support having two functions with the same name and different parameters. Since everything is an object only the name matters. Parameters are just metadata for the function.

You will have to have different names for those functions for this to work.

Why does Golang allow two functions to have the same name if they have different receiver types but not if they have different parameter types?

Disallowing methods of a concrete type with same name and different types is in the Go FAQ: Why does Go not support overloading of methods and operators?

Method dispatch is simplified if it doesn't need to do type matching as well. Experience with other languages told us that having a variety of methods with the same name but different signatures was occasionally useful but that it could also be confusing and fragile in practice. Matching only by name and requiring consistency in the types was a major simplifying decision in Go's type system.

Regarding operator overloading, it seems more a convenience than an absolute requirement. Again, things are simpler without it.

Allowing methods with same name of different types (with optionally identical parameter types, declared in the same package) is allowed for obvious reasons: bounding methods to a type naturally gives the method a "name space", the type they belong to.

If it would not be allowed, you could not declare multiple types in the same package that would implement the same interface(s). That would require putting them into different packages.



Related Topics



Leave a reply



Submit