28

Possible Duplicate:
function overloading in C

Apologies if this is a dup but if it is, I can't find it.

In C, can you define multiple functions with the same function name, but with different parameters? I come from a C# background. In C#, the following code is completely legal.

//Our first function

int MyFunction()
{
    //Code here
    return i;
}

int MyFunction(int passAParameter)
{
    // Code using passAParameter
    return i;
}

In my specific case, I would like to create a function that has one optional parameter (that is an int) at the end of the parameter list. Can this be done?

Community
  • 1
  • 1
RLH
  • 15,230
  • 22
  • 98
  • 182
  • 7
    No, sir function overloading is not allowed in C but it is allowed in C++. – Khaled Alshaya Sep 30 '11 at 18:44
  • It's called function overloading. Look here: http://stackoverflow.com/questions/479207/function-overloading-in-c – Matjaz Muhic Sep 30 '11 at 18:44
  • 1
    While the similar question in the link might have some hints on doing some sorts of overloading, you probably should stay away from it. Unlike C#, overloading is not idiomatic in C and it is perfectly acceptable to create two functions `MyFunction` and `MyFunctionWithParameter` – hugomg Sep 30 '11 at 18:53
  • Since this is closed I can not give you an "answer" but have to put this in a comment. The special case of optional parameters is possible to do with macro tricks. Have a look into P99, http://p99.gforge.inria.fr/ – Jens Gustedt Sep 30 '11 at 19:47

3 Answers3

55

No. C does not support overloading.

James McNellis
  • 348,265
  • 75
  • 913
  • 977
  • 3
    Whereas C has no overloading in general, the special case that OP asks for namely default arguments, can be done with macros in a convenient way. – Jens Gustedt Sep 30 '11 at 19:49
  • 2
    If you want to see how it's supported in C++, use the `nm` tool on unix-like OSs and you will see that the symbols built into ELF in C++ get mangled and have their type information added into the symbol name. If you ```extern "C"``` around the same symbols and build again and look, you'll noticed that the names are not mangled to include the argument types. – zjm555 Sep 09 '14 at 17:27
10

No. In strict C, you cannot do overloading.

However, given that most C compilers also support C++, and C++ does support overloading, there's a good chance you can do overloading if you're using a mainstream C/C++ compiler.

But its not strictly standard or portable to pure-C environments.

abelenky
  • 63,815
  • 23
  • 109
  • 159
3

No you must use a different name for each function (this is not true with C++, as it allows you to specify optional parameters)

Foo Bah
  • 25,660
  • 5
  • 55
  • 79