Reputation: 14778
Since C does not support method overloading, how is it possible to have methods like open
, that explicitly offers two different signatures:
int open(const char *pathname, int flags);
int open(const char *pathname, int flags, mode_t mode);
I mean, printf
supports a variate number of arguments using vargs
, but have no definite signature other than the one using vargs
itself -- otherwise there should be one signature for each possible printf
call. Yet, open()
-- as I presume -- is written in C, and offers two explicit signatures.
I didn't actually get the way these functions are implemented. Can someone show a small example of how a function like:
void foo() { printf("bar\n"); }
void foo(int x) { printf("bar %d\n", x); }
would be implemented in C?
Upvotes: 4
Views: 431
Reputation: 43548
You can not define function with the same name more than 1 time in the program as you mentioned in your question
Using macro will allow you to define function more than 1 time in the C code but only 1 function will compiled
#ifdef MACRO1
void foo() { printf("bar\n"); }
#else
void foo(int x) { printf("bar %d\n", x); }
#endif
and in the main
#ifdef MACRO1
foo();
#else
foo(5);
#endif
Upvotes: 0
Reputation:
how is it possible to have methods like open, that explicitly offers two different signatures:
Wait, wait, wait... nah. Not even close. How'bout reading the documentation?
open()
is a variadic function, its signature is
int open(const char *path, int oflag, ... );
No magic here.
Upvotes: 1
Reputation: 613262
You've picked a poor reference (http://linux.die.net) to learn about this function. A better one is the Open Group Base Specifications. And it shows this declaration for open()
:
int open(const char *path, int oflag, ... );
So in other words, this is just varargs.
Upvotes: 1
Reputation: 7698
It is all varargs based. In the case of open, it only reads the third argument for certain inputs and states. In particular, when it has to create the file. Similarly, printf only reads the arguments when it scans the % format markers. Your case doesn't really work that way as there is no early argument to indicate how many arguments there are.
Upvotes: 0
Reputation: 726809
The function open
is defined with a variable number of arguments:
int open(const char *_path, int _oflag, ...)
Here is a source of <fcntl.h>
; the function open
is declared at the bottom using the _PROTOTYPE
macro.
Note that part of the reason it works with open
is that the function takes other parameters already. In order for the function to take variable number of arguments, it must take at least one "fixed" argument. That is why it is not possible to do this trick with your foo()
function.
Upvotes: 4