Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

About function overloading in c

Tags:

c

linux

I'm reading the man page of the open() syscall, and I noticed that there are 2 types of the function in the man page :

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

I know that in C there isn't function overloading. How can there be 2 declarations of open()? Thanks!

like image 254
Ido Shany Avatar asked Dec 23 '22 20:12

Ido Shany


1 Answers

open is actually declared as a variadic function. If you look in <fcntl.h> you will see something like

extern int open (const char *pathname, int flags, ...);

So as far as the syntax is concerned, any arguments after the first two are optional.

The declarations in the man page are meant to tell you that in order for the function to actually work correctly, you should pass either no additional arguments, or one additional argument of type mode_t. (The rest of the man page explains how to determine when to do which.)

You are quite right that there is no function overloading in C, and in fact the open function does not actually know how many arguments you called it with. Instead* it looks at whether the O_CREAT bit is set in the flags argument, and if it is, it knows to expect a third argument, telling it what modes the newly created file should have. It can then obtain the value of this argument using va_arg and friends (or in some other system-specific way). Of course, if you specify O_CREAT but don't actually pass a third argument, or pass an argument of a different type than mode_t, the compiler won't stop you, but something will probably go wrong when the function executes.

* There may be other conditions under which a third argument will be expected, e.g. when using the O_TMPFILE flag, but O_CREAT is by far the most common.

like image 131
Nate Eldredge Avatar answered Jan 04 '23 02:01

Nate Eldredge