2

Possible Duplicate:
What is the signature of printf?
Does C support overloading?
Does printf support function overloading In C?

C's printf function seems to show method overloading as different types of arguments can be given to it. Is this right or printf is something else?

Community
  • 1
  • 1
Shashank Jain
  • 847
  • 2
  • 10
  • 25
  • 1
    printf uses the ellipsis operator (...) - http://linuxprograms.wordpress.com/2008/03/07/c-ellipsis-operator-printf/ – arunkumar Aug 31 '11 at 09:36

3 Answers3

8

printf()is something else that is called variadic function. The exact number and types of its arguments is specified through its first one, the format.

Other variadic functions have other ways of specifying number and/or type of arguments but it is always through one fixed argument.

mouviciel
  • 66,855
  • 13
  • 106
  • 140
5

It's not method overloading at all. Method overloading respects types. printf just flat out ignores them and hopes you got it right in the format specifier.

Puppy
  • 144,682
  • 38
  • 256
  • 465
2

printf is a variadic function, so it determines at run-time how many arguments to expect based on the format specifier you give it.

Whether that counts as "overloading" depends on your definition! Most people would say it isn't, because it's nothing to do with the compiler (only one function is instantiated in binary). But from the user's perspective, it still acts a lot like overloading (just not type-safe).

Oliver Charlesworth
  • 267,707
  • 33
  • 569
  • 680
  • 1
    type safety is extremely important. Acting like overloading but not type safe would be like having sex but not having fun. – Puppy Aug 31 '11 at 09:48
  • 1
    How can it be overloading when there is only one printf? – Nicola Musatti Aug 31 '11 at 09:51
  • @Nicola: Why does the underlying implementation matter? As far as the user is concerned, variadic functions can have some of the characteristics of "true" overloaded functions (the [`open()` sys-call](http://linux.die.net/man/2/open) is a good example of this). – Oliver Charlesworth Aug 31 '11 at 09:55
  • Depends on your definition of overloading ;-) – Nicola Musatti Aug 31 '11 at 09:57
  • @Oli: overloading means to use the same name for more than one thing; it is commonly used to indicate the possibility of defining functions with the same name, provided their argument types and/or number is different. C doesn't support overloading and the standard C library is defined so that it may be implemented in C itself. Variadic functions with unconstrained argument types are a different way to achieve a similar effect. In the context of implementation techniques, which in my opinion is underlying the OP's question, confusing the two concepts is misleading. – Nicola Musatti Aug 31 '11 at 14:32