3
votes

I read that C doesn't suppose function overloading. But in this Slide we can see it's not correct and my professor said: "How Is it possible that we have 2 different signatures for same function name in C?"

enter image description here

Can someone explain this?

1
The open function in this respect is more like printf: a single function that accepts a variable number of arguments. For printf, the number of %-specifiers in the format string tells printf how many more arguments to expect. For open, the presence of the O_CREAT bit in flags tells it whether to expect the third mode argument.Steve Summit
From Optional arguments in C function: "If you look today at recent implementation of that open function in free software libc implementations on Linux, such as musl-libc, you see in its src/fcntl/open.c that it uses the <stdarg.h> variadic facilities (which are often implemented as compiler builtins."mediocrevegetable1

1 Answers

6
votes

It isn't possible. Code such as this:

int open(const char* path, int flags);
int open(const char* path, int flags, mode_t mode);

is invalid C and will not compile (but valid C++).

However, C supports variadic functions and the old open function is implemented using that. It's actually declared as:

int open(const char *path, int oflag, ... );

Where the ... allows a variable amount of arguments through the features of stdarg.h.