Go Premium for a chance to win a PS4. Enter to Win

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 525
  • Last Modified:

Pure C - function with optional arguments only


I want to declare a function, which has no required parameters, but may have optional, and do it in pure C.

It's simple for functions having at least one parameter:
   void my_func( char *sFirst, ... );
and then accessing the optional using arg_list.

I want to define something like
   void my_func( ... );
but it's not valid :(

I'll appreciate your help.
2 Solutions
man 3 getopt

something like
while ((ch = getopt(argc, argv, "a:dhf:l:m:np:rs:v")) != EOF)
should serve your purpose

the above line of code is from syslogd source code
hey you can always declare a pointer to a function without no args e.g

void ( * function)();

void  a_function_implementation(int  param1);
   // The param may not have been passed so the question is how
  // do you intend to find out wether a param has been passed or not;

int main(int argc,char* argv[])
    function = a_function_implementation;
migoEXAuthor Commented:
There is 1 problem left:

I want this function to be exported, and used by "external" functions. If in my H file I declare the function without parameters, the caller won't be able to compile a code, which is passing parameter. And vise versa - if I define it with parameter, a call without passing parameters won't compile.

PS: I'm not sure it's possible :)  but may be I'm missing some solution
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Even I would be interested in the solution if this was possible ...
You can declare the function with an empty argument list, eg

void myfunc();

In C (not C++) this functions takes any number of arguments. The above means "arguments are still unspecified". You can specify the arguments later on when defining the function.

The above is also the reason that functions without arguments should be defined as

void myfunc(void);
migoEXAuthor Commented:
Thanks, mtmike!

That's exactly what I was looking for :)

Featured Post

Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now